<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Models\StorePlatform;
use App\Services\CropQuotaService;

class PaymentApiController extends BaseApiController
{

    /**
     * 根据平台代码获取平台配置信息
     * 按照老项目 PlatformController 的 getPlatformCode 方法逻辑实现（第223-240行）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getPlatformCode(Request $request)
    {
        try {
            // 获取平台代码 - 按照老项目第225行
            $platformcode = $this->getParam($request, 'platformcode');
            
            if (empty($platformcode)) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '平台代码不能为空',
                    'data'   => []
                ]);
            }

            // 查询平台信息 - 按照老项目第226行
            $platform_model = StorePlatform::where('platformcode', $platformcode)->first();
            
            // 验证平台是否存在 - 按照老项目第227-229行
            if (empty($platform_model)) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '编辑：未找到平台',
                    'data'   => []
                ]);
            }

            // 构建返回数据 - 按照老项目第230-238行
            $authorizationLimit = $platform_model->getAttribute('authorizationlimit');
            if ($authorizationLimit === null) {
                $authorizationLimit = $platform_model->getAttribute('authorization_limit');
            }
            $data = [
                'platformcode'       => $platform_model->platformcode,
                'authorizationlimit' => $authorizationLimit,
                'yhexchangelt'       => $platform_model->yhexchangelt,
                'yhexchangert'       => $platform_model->yhexchangert,
                'yhpromolt'          => $platform_model->yhpromolt,
                'yhpromort'          => $platform_model->yhpromort,
                'id'                 => $platform_model->id,
            ];

            // 返回成功响应 - 按照老项目第239行
            return response()->json([
                'result' => 1,
                'msg'    => '',
                'data'   => $data
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 验证平台代码是否有效
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function validatePlatformCode(Request $request)
    {
        try {
            $platformcode = $this->getParam($request, 'platformcode');
            
            if (empty($platformcode)) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '平台代码不能为空',
                    'data'   => ['valid' => false]
                ]);
            }

            // 查询平台是否存在
            $exists = StorePlatform::where('platformcode', $platformcode)->exists();
            
            return response()->json([
                'result' => 1,
                'msg'    => $exists ? '平台代码有效' : '平台代码无效',
                'data'   => ['valid' => $exists]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '验证失败: ' . $e->getMessage(),
                'data'   => ['valid' => false]
            ]);
        }
    }

    /**
     * 获取支付平台列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getPlatformList(Request $request)
    {
        try {
            $page = max(1, (int) $this->getParam($request, 'page', 1));
            $limit = max(1, min(50, (int) $this->getParam($request, 'limit', 10)));
            
            $cacheKey = "payment:platform_list:{$page}:{$limit}";
            $cached = Cache::get($cacheKey);
            
            if ($cached) {
                $cached['from_cache'] = true;
                return response()->json([
                    'result' => 1,
                    'msg'    => '获取成功',
                    'data'   => $cached
                ]);
            }

            // 查询平台列表
            $platforms = StorePlatform::select([
                'id', 'platformcode', 'platformname', 'applyname', 
                'authorizationlimit', 'status', 'created_at'
            ])
            ->where('status', 1)
            ->orderBy('created_at', 'desc')
            ->paginate($limit, ['*'], 'page', $page);

            $result = [
                'list' => $platforms->items(),
                'pagination' => [
                    'current_page' => $platforms->currentPage(),
                    'last_page'    => $platforms->lastPage(),
                    'per_page'     => $platforms->perPage(),
                    'total'        => $platforms->total(),
                ],
                'from_cache' => false
            ];
            
            Cache::put($cacheKey, $result, 300); // 缓存5分钟
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 获取收银台支付设置信息
     * 按照老项目 CenterController 的 getPaySet 方法逻辑实现（第176-192行）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getPaySet(Request $request)
    {
        try {
            // 获取参数 - 按照老项目第178-179行
            $hotel_id = (int) $this->getParam($request, 'hotel_id', 0);
            $store_id = (int) $this->getParam($request, 'store_id', 0);
            
            $apiData = [];
            
            // 获取酒店信息（如果提供了hotel_id）- 按照老项目第181-185行
            if ($hotel_id) {
                // 老项目调用 Hotel 插件的 CenterController::index
                // 这里暂不实现，保留接口
                $apiData['get_hotel_info'] = [
                    'hotel_id' => $hotel_id,
                    'message' => '酒店信息获取功能待实现'
                ];
            }
            
            // 获取门店信息（如果提供了store_id）- 按照老项目第186-188行
            if ($store_id) {
                $storeInfoResult = $this->getStoreInfoForPaySet($store_id);
                if (isset($storeInfoResult['error']) && $storeInfoResult['error']) {
                    return response()->json([
                        'result' => 0,
                        'msg'    => $storeInfoResult['message'],
                        'data'   => []
                    ]);
                }
                $apiData['get_store_info'] = $storeInfoResult;
            }
            
            // 获取支付协议信息 - 按照老项目第190行
            $payProtocolResult = $this->getPayProtocol();
            $apiData['get_pay_protocol'] = $payProtocolResult;
            
            return response()->json([
                'result' => 1,
                'msg'    => '',
                'data'   => $apiData
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => []
            ]);
        }
    }


    
    /**
     * 获取门店信息（收银台付款页面专用，不统计门店订单）
     * 按照老项目 CenterController 的 getStoreInfo 方法逻辑实现（第195-252行）
     *
     * @param int $store_id
     * @return array
     */
    private function getStoreInfoForPaySet($store_id)
    {
        try {
            // 查询门店信息 - 按照老项目第197-214行
            if ($store_id) {
                $store = \App\Models\Store::where('id', $store_id)->first();
            } else {
                // 如果没有提供store_id，根据当前用户ID查询
                $uid = request()->get('uid', 0);
                $store = \App\Models\Store::where('uid', $uid)->first();
            }
            
            // 验证门店 - 按照老项目第215-229行
            if (!$store) {
                return [
                    'error' => true,
                    'message' => '门店不存在'
                ];
            }
            
            if (isset($store->is_black) && $store->is_black == 1) {
                return [
                    'error' => true,
                    'message' => '门店已进入黑名单'
                ];
            }
            
            // 获取收银台商品配置 - 按照老项目第231行
            $cashierGoods = \App\Models\CashierGoods::where('goods_id', $store->cashier_id)->first();
            
            // 构建返回数据 - 按照老项目第233-246行
            return [
                'store' => [
                    'name'      => $store->store_name ?? '',
                    'thumb'     => $store->thumb ?? '',
                    'mobile'    => $store->mobile ?? '',
                    'store_id'  => $store->id
                ],
                'store_set' => [
                    'is_write_information'  => $cashierGoods ? ($cashierGoods->is_write_information ?? 0) : 0,
                    'is_open_cashier'       => $cashierGoods ? ($cashierGoods->is_open ?? 0) : 0,
                    'is_cash_pay'           => $cashierGoods ? ($cashierGoods->is_cash_pay ?? 0) : 0,
                    'payment_types'         => []
                ]
            ];
            
        } catch (\Exception $e) {
            return [
                'error' => true,
                'message' => '获取门店信息失败: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * 获取支付协议信息
     *
     * @return array
     */
    private function getPayProtocol()
    {
        try {
            // 这里需要根据实际的支付协议获取逻辑来实现
            // 提供一个基础的返回结构
            return [
                'protocol_content' => '支付协议内容',
                'version' => '1.0',
                'updated_at' => date('Y-m-d H:i:s')
            ];
            
        } catch (\Exception $e) {
            return [
                'error' => true,
                'message' => '获取支付协议失败: ' . $e->getMessage()
            ];
        }
    }


    /**
     * 根据平台代码获取关联关系
     * 按照老项目 PlatformController 的 getRelationByCode 方法逻辑实现（第116-136行）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getRelationByCode(Request $request)
    {
        try {
            // 获取参数 - 按照老项目第118-120行
            $memberUid = $this->getParam($request, 'uid');
            $store_id = $this->getParam($request, 'store_id');
            $platform_code = $this->getParam($request, 'platform_code');
            
            // 查询门店信息 - 按照老项目第121行
            $record = \App\Models\Store::where('id', $store_id)->first();
            if (!$record) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店不存在',
                    'data'   => []
                ]);
            }
            
            // 解析门店的平台ID列表 - 按照老项目第122-123行
            $platform_idsStr = $record->platform_ids;
            $platform_idsList = explode(",", $platform_idsStr);
            
            // 查询平台信息 - 按照老项目第124-125行
            $platform_model = StorePlatform::where('platformcode', $platform_code)->first();
            if (!$platform_model) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '平台代码不存在',
                    'data'   => []
                ]);
            }
            
            $platform_id = $platform_model->id;
            
            // 再次解析平台ID列表（老项目第126-127行重复了，保持一致）
            $platform_idsStr = $record->platform_ids;
            $platform_idsList = explode(",", $platform_idsStr);
            
            // 检查门店与平台的关联关系 - 按照老项目第128-131行
            $relation = null;
            if (in_array($platform_id, $platform_idsList)) {
                $relation = $platform_model;
            }
            
            // 查询会员信息 - 按照老项目第132行
            $member = \App\Models\Member::where('uid', $memberUid)->first();
            
            // 构建返回结果 - 按照老项目第133-134行
            $res['relation'] = $relation;
            $res['member'] = $member;
            
            // 返回成功响应 - 按照老项目第135行
            return response()->json([
                'result' => 1,
                'msg'    => '',
                'data'   => $res
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 收银台商品购买
     * 按照老项目 GoodsBuyController 的 index 方法逻辑实现（第99-129行）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function goodsBuy(Request $request)
    {
        try {
            // 验证参数 - 按照老项目第52-58行
            $store_id = (int) $this->getParam($request, 'store_id', 0);
            $price = (float) $this->getParam($request, 'price', 0);
            $type = (int) $this->getParam($request, 'type', 0);
            $buy_id = (int) $this->getParam($request, 'buy_id', 0);
            
            if (!$store_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => 'store_id参数必填',
                    'data'   => []
                ]);
            }
            
            if ($price < 0.01) {
                return response()->json([
                    'result' => 0,
                    'msg'    => 'price参数必须大于等于0.01',
                    'data'   => []
                ]);
            }
            
            // 验证价格格式（最多两位小数） - regex:/^[0-9]+(.[0-9]{1,2})?$/
            if (!preg_match('/^[0-9]+(\.[0-9]{1,2})?$/', $price) || $price > 99999999.99) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '价格格式不正确',
                    'data'   => []
                ]);
            }
            
            // 验证门店（verify方法） - 按照老项目第80-93行
            $store = \App\Models\Store::find($store_id);
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店不存在',
                    'data'   => []
                ]);
            }
            
            if (isset($store->is_black) && $store->is_black == 1) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '收银台已进入黑名单',
                    'data'   => []
                ]);
            }
            
            // 检查收银台商品ID - 按照老项目第66-69行
            $cashier_goods_id = $store->cashier_id ?? null;
            if (!$cashier_goods_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '请先配置收银台信息',
                    'data'   => []
                ]);
            }
            
            // 检查最低消费限制 - 按照老项目第90-92行
            $cashierGoods = \App\Models\CashierGoods::where('goods_id', $cashier_goods_id)->first();
            if ($cashierGoods && isset($cashierGoods->every_min_money) && $cashierGoods->every_min_money > $price) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '商家设置单次最低消费' . $cashierGoods->every_min_money . '元',
                    'data'   => []
                ]);
            }
            
            // 获取会员信息 - 按照老项目第102-112行
            $member = null;
            if ($type == 9 && $buy_id) {
                $member = \App\Models\Member::find($buy_id);
                if (!$member) {
                    $member = new \App\Models\Member(['uid' => 0]);
                }
            } else {
                $uid = $this->getParam($request, 'uid', 0);
                if ($uid) {
                    $member = \App\Models\Member::find($uid);
                }
            }
            
            // 获取会员购物车的交易数据 - 按照老项目第109-112行
            // 这里需要调用 MemberCartService 和 getTrade 方法
            // 由于新项目可能没有这些服务，我们简化处理
            $trade = $this->getMemberCartsTrade($store_id, $cashier_goods_id, $price, $member);
            
            // 按照老项目第114-118行：合并订单抵扣
            $allOrderDeductions = [];
            foreach ($trade['orders'] as $order) {
                foreach ($order['order_deductions'] as $deductions) {
                    $allOrderDeductions[] = $deductions;
                }
            }
            $trade['order_deductions'] = $allOrderDeductions;
            
            // 按照老项目第119-124行：过滤金额明细项
            $filteredAmountItems = [];
            foreach ($trade['amount_items'] as $key => $amount_item) {
                if (!in_array($amount_item['code'], ['total_goods_price', 'total_dispatch_price'])) {
                    $filteredAmountItems[] = $amount_item;
                }
            }
            $trade['amount_items'] = $filteredAmountItems;
            
            // 按照老项目第125-126行：获取会员余额
            $memberBalance = 0;
            if ($member && $member->uid) {
                $memberModel = \App\Models\Member::find($member->uid);
                $memberBalance = $memberModel ? (float)($memberModel->credit2 ?? 0) : 0;
            }
            $trade['balance'] = $memberBalance;
            
            return response()->json([
                'result' => 1,
                'msg'    => '成功',
                'data'   => $trade
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 获取会员购物车交易数据
     * 对应老项目的 getMemberCarts()->getTrade() 方法
     * 
     * @param int $storeId 门店ID
     * @param int $goodsId 商品ID
     * @param float $price 价格
     * @param object|null $member 会员对象
     * @return array
     */
    private function getMemberCartsTrade($storeId, $goodsId, $price, $member)
    {
        // 构建订单数据
        $orderData = [
            'order_id' => 'temp_' . time(),
            'store_id' => $storeId,
            'goods_price' => $price,
            'dispatch_price' => 0,
            'discount_price' => 0,
            'deduction_price' => 0,
            'order_deductions' => [] // 每个订单的抵扣
        ];
        
        // 金额明细项
        $amountItems = [];
        
        // 商品总价
        $amountItems[] = [
            'code' => 'total_goods_price',
            'name' => '商品总价',
            'value' => $price,
            'value_str' => '¥' . number_format($price, 2)
        ];
        
        // 商品金额
        $amountItems[] = [
            'code' => 'goods_price',
            'name' => '商品金额',
            'value' => $price,
            'value_str' => '¥' . number_format($price, 2)
        ];
        
        // 运费
        $amountItems[] = [
            'code' => 'total_dispatch_price',
            'name' => '运费',
            'value' => 0,
            'value_str' => '¥0.00'
        ];
        
        // 应付金额
        $amountItems[] = [
            'code' => 'total_price',
            'name' => '应付金额',
            'value' => $price,
            'value_str' => '¥' . number_format($price, 2)
        ];
        
        return [
            'orders' => [$orderData],
            'order_deductions' => [],
            'amount_items' => $amountItems,
            'total_price' => $price,
            'goods_price' => $price,
            'dispatch_price' => 0,
            'discount_price' => 0,
            'deduction_price' => 0
        ];
    }
    
    /**
     * 获取支付方式列表
     * 按照老项目 ListController 的 index 方法逻辑实现（第24-84行）
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function paymentList(Request $request)
    {
        try {
            $store_id = (int) $this->getParam($request, 'store_id', 0);
            $price = (float) $this->getParam($request, 'price', 0.01);
            
            if (!$store_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店ID不能为空',
                    'data'   => []
                ]);
            }
            
            // 查询门店信息 - 按照老项目第30行
            $store = \App\Models\Store::where('id', $store_id)->first();
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店不存在',
                    'data'   => []
                ]);
            }
            
            $result = [];
            
            // 沐浴露支付方式定义 - 按照老项目第31-37行
            $item = [
                'code'          => 'yyg',
                'name'          => '沐浴露',
                'value'         => 137,
                'need_password' => '',
                'weight'        => 1002,
            ];
            
            // 查询门店的置换类型配置 - 按照老项目第38-43行
            $properties = \App\Models\StoreCashierSwitchCodeGroupProperties::select([
                    'ims_yz_store_cashier_switch_code_group_properties.in_type'
                ])
                ->leftJoin('ims_yz_store_cashier_switch_code_group_relation', 
                    'ims_yz_store_cashier_switch_code_group_relation.group_propertie_id', '=', 
                    'ims_yz_store_cashier_switch_code_group_properties.id')
                ->where('ims_yz_store_cashier_switch_code_group_relation.store_id', $store_id)
                ->where('ims_yz_store_cashier_switch_code_group_relation.state', 1)
                ->get();
            
            \Log::info('门店置换配置查询结果', [
                'store_id' => $store_id,
                'properties_count' => $properties->count(),
                'properties' => $properties->toArray()
            ]);
            // 根据配置生成支付方式列表 - 按照老项目第44-51行
            foreach ($properties as $propertie) {
                if ($propertie->in_type == 133) {
                    // 茶包支付方式
                    $result = array_merge($result, $this->getCashierPaymentButtons($price));
                    \Log::info('添加茶包支付方式');
                }
                if ($propertie->in_type == 137) {
                    // 沐浴露支付方式
                    $result[] = $item;
                    \Log::info('添加沐浴露支付方式');
                }
                if ($propertie->in_type == 138) {
                    // 额度支付方式
                    $result[] =  [
                        'code'          => 'quota',
                        'name'          => '额度',
                        'value'         => 138,
                        'need_password' => '',
                        'weight'        => 1002,
                    ];
                    \Log::info('添加额度支付方式');
                }
            }
            
            \Log::info('最终支付方式列表', [
                'result_count' => count($result),
                'result' => $result
            ]);
            
            // 如果没有配置任何支付方式，返回空数组
            // 注意：老项目第78-80行被注释掉，如果没有配置会返回空数组
            // if (count($result) == 0) {
            //     return $this->errorJson('置换方式未设置，请联系管理员');
            // }
            
            return response()->json([
                'result' => 1,
                'msg'    => '成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 获取收银台支付按钮
     * 对应老项目第46行的 app('Payment')->setPaymentTypes(new CashierOrderPaymentTypes($orderPay))->getPaymentButton()
     * 
     * @param float $price 订单金额
     * @return array
     */
    private function getCashierPaymentButtons($price)
    {
        // 创建虚拟订单支付对象
        // 对应老项目第26行：OrderPay::newVirtual(request()->input('price', 0.01))
        $orderPay = new \App\Models\OrderPay();
        $orderPay->amount = $price;
        $orderPay->status = 0;
        
        // 这里应该调用支付工厂获取收银台支付方式
        // 由于涉及到老项目的 PayFactory 和 CashierOrderPaymentTypes
        // 暂时返回茶包支付方式
        return [
            [
                'code'          => 'balance',
                'name'          => '茶包',
                'value'         => 133,
                'need_password' => '',
                'weight'        => 1001,
            ]
        ];
    }

    /**
     * 获取置换类型列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function swapTypes(Request $request)
    {
        try {
            $store_id = (int) $this->getParam($request, 'store_id', 0);
            
            if (!$store_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店ID不能为空',
                    'data'   => []
                ]);
            }
            
            // 查询门店信息
            $store = \App\Models\Store::find($store_id);
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店不存在',
                    'data'   => []
                ]);
            }
            
            // 获取置换类型列表
            $swapTypes = $this->getSwapTypes($store_id);
            
            return response()->json([
                'result' => 1,
                'msg'    => '获取成功',
                'data'   => $swapTypes
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 获取支付方式按钮列表
     *
     * @param int $store_id
     * @return array
     */
    private function getPaymentButtons($store_id)
    {
        try {
            // 这里需要根据实际的支付方式配置来实现
            // 提供一个基础的支付方式列表
            $buttons = [
                [
                    'code' => 'wechat',
                    'name' => '微信支付',
                    'icon' => 'wechat-icon',
                    'enabled' => true,
                    'sort' => 1
                ],
                [
                    'code' => 'alipay',
                    'name' => '支付宝',
                    'icon' => 'alipay-icon',
                    'enabled' => true,
                    'sort' => 2
                ],
                [
                    'code' => 'balance',
                    'name' => '余额支付',
                    'icon' => 'balance-icon',
                    'enabled' => true,
                    'sort' => 3
                ],
                [
                    'code' => 'cash',
                    'name' => '现金支付',
                    'icon' => 'cash-icon',
                    'enabled' => true,
                    'sort' => 4
                ]
            ];
            
            // 根据门店配置过滤支付方式
            // 这里可以根据实际需求添加门店特定的支付方式配置逻辑
            
            return $buttons;
            
        } catch (\Exception $e) {
            return [
                [
                    'code' => 'cash',
                    'name' => '现金支付',
                    'icon' => 'cash-icon',
                    'enabled' => true,
                    'sort' => 1
                ]
            ];
        }
    }

    /**
     * 创建订单
     * 按照老项目 plugin.store-cashier.frontend.Order.create 接口逻辑实现
     * 实际数据库操作，不返回模拟数据
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function createOrder(Request $request)
    {
        try {
            $store_id = (int) $this->getParam($request, 'store_id', 0);
            $price = (float) $this->getParam($request, 'price', 0);
            $member_coupon_ids = $this->getParam($request, 'member_coupon_ids', []);
            $orders = $this->getParam($request, 'orders', '[]');
            $mobile = $this->getParam($request, 'mobile', '');
            $realname = $this->getParam($request, 'realname', '');
            
            // 参数验证 - 按照老项目逻辑：price >= 0.01, <= 99999999.99, 最多两位小数
            if (!$store_id || $price < 0.01) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '参数不完整或价格无效（最低0.01元）',
                    'data'   => []
                ]);
            }
            
            // 验证价格格式（最多两位小数） - 正则：/^[0-9]+(.[0-9]{1,2})?$/
            if (!preg_match('/^[0-9]+(\.[0-9]{1,2})?$/', $price) || $price > 99999999.99) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '价格格式不正确（最多两位小数，最大99999999.99）',
                    'data'   => []
                ]);
            }
            
            // 查询门店信息
            $store = \App\Models\Store::find($store_id);
            if (!$store) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店不存在',
                    'data'   => []
                ]);
            }
            
            // 验证门店状态
            if (isset($store->is_black) && $store->is_black == 1) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '收银台已进入黑名单',
                    'data'   => []
                ]);
            }
            
            // 检查最低消费限制
            if (isset($store->every_min_money) && $store->every_min_money > $price) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '商家设置单次最低消费' . $store->every_min_money . '元',
                    'data'   => []
                ]);
            }
            
            // 获取收银台商品ID
            $cashier_goods_id = $store->cashier_id ?? null;
            if (!$cashier_goods_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '请先配置收银台信息',
                    'data'   => []
                ]);
            }
            
            // 获取当前会员信息
            $uid = $this->getParam($request, 'uid', 0); // 从入参获取用户ID
            $member = \App\Models\Member::find($uid);
            
            // 使用数据库事务确保数据一致性
            $result = \DB::transaction(function () use ($store_id, $price, $cashier_goods_id, $member, $mobile, $realname, $store, $member_coupon_ids, $orders, $uid) {
                
                // 生成订单号 - 按照老项目格式
                $order_sn = 'SN' . date('ymdHis') . strtoupper(substr(md5(uniqid()), 0, 4));
                
                // 创建订单记录 - 按照老项目Order表结构
                $order = new \App\Models\Order();
                $order->plugin_id = 31; // 收银台插件ID
                $order->is_virtual = 1; // 虚拟商品
                $order->uid = $uid; // 从入参获取用户ID
                $order->uniacid = 1; // 默认小程序ID
                $order->dispatch_type_id = 0;
                $order->mark = '';
                $order->goods_price = $price;
                $order->price = $price;
                $order->order_goods_price = $price;
                $order->vip_order_goods_price = $price;
                $order->cost_amount = $price;
                $order->discount_price = 0;
                $order->fee_amount = 0;
                $order->service_fee_amount = 0;
                $order->deduction_price = 0;
                $order->dispatch_price = 0;
                $order->goods_total = 1;
                $order->no_refund = 0;
                $order->order_sn = $order_sn;
                $order->create_time = time();
                $order->note = '';
                $order->shop_name = '收银台-' . ($store->store_name ?? '');
                $order->need_address = 0;
                $order->invoice_type = 0;
                $order->rise_type = 0;
                $order->collect_name = '';
                $order->company_number = '';
                $order->paytype = 0;
                $order->dkfee = 0;
                $order->mid = $store_id; // 门店ID
                $order->updated_at = time();
                $order->created_at = time();
                $order->status = 0; // 待支付
                $order->save();
                
                // 创建订单发票记录
                $orderInvoice = new \App\Models\OrderInvoice();
                $orderInvoice->uniacid = 1;
                $orderInvoice->uid = $uid;
                $orderInvoice->invoice_type = 0;
                $orderInvoice->email = '';
                $orderInvoice->rise_type = 1;
                $orderInvoice->collect_name = '';
                $orderInvoice->enterprise_id = '';
                $orderInvoice->invoice_sn = '';
                $orderInvoice->equipment_number = '';
                $orderInvoice->xsf_name = '';
                $orderInvoice->xsf_taxpayer = '';
                $orderInvoice->xsf_address = '';
                $orderInvoice->xsf_mobile = '';
                $orderInvoice->xsf_bank_admin = '';
                $orderInvoice->content = '';
                $orderInvoice->drawer = '';
                $orderInvoice->payee = '';
                $orderInvoice->reviewer = '';
                $orderInvoice->bill_type = 0;
                $orderInvoice->special_type = 0;
                $orderInvoice->collection = 0;
                $orderInvoice->list_identification = 0;
                $orderInvoice->gmf_taxpayer = '';
                $orderInvoice->gmf_address = '';
                $orderInvoice->gmf_bank = '';
                $orderInvoice->gmf_bank_admin = '';
                $orderInvoice->gmf_mobile = '';
                $orderInvoice->remarks = '';
                $orderInvoice->notice_no = '';
                $orderInvoice->applicant = '';
                $orderInvoice->is_audit = 0;
                $orderInvoice->tax_rate = 0;
                $orderInvoice->zero_tax_rate = 0;
                $orderInvoice->invoice_no = '';
                $orderInvoice->invoice_nature = 0;
                $orderInvoice->status = 0;
                $orderInvoice->apply = 0;
                $orderInvoice->col_address = '';
                $orderInvoice->col_name = '';
                $orderInvoice->col_mobile = '';
                $orderInvoice->detail_param = '';
                $orderInvoice->invoice_time = time();
                $orderInvoice->order_id = $order->id;
                $orderInvoice->need_invoice = 0;
                $orderInvoice->updated_at = time();
                $orderInvoice->created_at = time();
                $orderInvoice->save();
                
                // 创建订单地址记录 - 按照老项目逻辑，从门店信息获取地址
                $orderAddress = new \App\Models\OrderAddress();
                $orderAddress->street_id = $store->street_id ?? 0;
                $orderAddress->zipcode = '';
                
                // 构建完整地址：省市区 + 详细地址
                $addressParts = [];
                if ($store->province_id) {
                    $province = \App\Models\Address::find($store->province_id);
                    if ($province) $addressParts[] = $province->areaname;
                }
                if ($store->city_id) {
                    $city = \App\Models\Address::find($store->city_id);
                    if ($city) $addressParts[] = $city->areaname;
                }
                if ($store->district_id) {
                    $district = \App\Models\Address::find($store->district_id);
                    if ($district) $addressParts[] = $district->areaname;
                }
                if ($store->address) {
                    $addressParts[] = $store->address;
                }
                $orderAddress->address = implode(' ', $addressParts) ?: '地址未配置';
                
                $orderAddress->mobile = $mobile ?: '';
                $orderAddress->province_id = $store->province_id ?? 0;
                $orderAddress->city_id = $store->city_id ?? 0;
                $orderAddress->district_id = $store->district_id ?? 0;
                $orderAddress->realname = $realname ?: '';
                $orderAddress->order_id = $order->id;
                $orderAddress->updated_at = time();
                $orderAddress->created_at = time();
                $orderAddress->save();
                
                // 创建门店订单关联记录
                $storeOrder = new \App\Models\StoreOrder();
                $storeOrder->store_id = $store_id;
                $storeOrder->order_id = $order->id;
                $storeOrder->updated_at = time();
                $storeOrder->created_at = time();
                $storeOrder->save();
                
                // 创建收银台订单记录
                $cashierOrder = new \App\Models\CashierOrder();
                $cashierOrder->realname = $realname;
                $cashierOrder->mobile = $mobile;
                $cashierOrder->cashier_id = $cashier_goods_id;
                $cashierOrder->order_id = $order->id;
                
                // 获取收银台商品配置 - 按照老项目逻辑
                $cashierGoods = \App\Models\CashierGoods::where('goods_id', $cashier_goods_id)->first();
                $shopCommission = $cashierGoods ? (float)($cashierGoods->shop_commission ?? 0) : 0;
                $settlementDay = $cashierGoods ? (int)($cashierGoods->settlement_day ?? 0) : 0;
                
                // 获取提现模式 - 按照老项目逻辑从Setting::get('plugin.store')获取
                // 从 ims_yz_setting 表中查询 group='plugin', key='store' 的配置
                $pluginStoreConfig = \App\Models\Setting::get('plugin.store', []);
                $withdrawMode = isset($pluginStoreConfig['withdraw_mode']) 
                    ? (int)$pluginStoreConfig['withdraw_mode'] 
                    : 0; // 默认值：基于商品价格计算手续费
                
                $cashierOrder->fee_percentage = $shopCommission;
                $cashierOrder->settlement_days = $settlementDay;
                $cashierOrder->withdraw_mode = $withdrawMode;
                
                // 计算手续费和金额 - 按照老项目PreCashierOrder::save逻辑
                if (!$withdrawMode || $withdrawMode == 3) {
                    // 基于商品价格计算
                    $cashierOrder->fee = $this->proportionMath($price, $shopCommission);
                    $cashierOrder->amount = $price - $cashierOrder->fee;
                } elseif ($withdrawMode == 4) {
                    // 基于商品实际支付金额计算
                    $cashierOrder->fee = $this->proportionMath($price, $shopCommission);
                    $cashierOrder->amount = $price - $cashierOrder->fee;
                } else {
                    // 基于订单价格减去费用后计算（withdrawMode == 1, 2等）
                    $feeAmount = $order->fee_amount ?? 0;
                    $baseAmount = $price - $feeAmount;
                    $cashierOrder->fee = $this->proportionMath($baseAmount, $shopCommission);
                    $cashierOrder->amount = $baseAmount - $cashierOrder->fee;
                }
                
                $cashierOrder->updated_at = time();
                $cashierOrder->created_at = time();
                $cashierOrder->save();
                
                // 创建订单插件记录
                $orderPlugin = new \App\Models\OrderPlugin();
                $orderPlugin->main_plugin_id = 31;
                $orderPlugin->sub_plugin_id = 31;
                $orderPlugin->order_id = $order->id;
                $orderPlugin->updated_at = time();
                $orderPlugin->created_at = time();
                $orderPlugin->save();
                
                // 创建订单请求记录
                $orderRequest = new \App\Models\OrderRequest();
                $orderRequest->request = json_encode([
                    'i' => '1',
                    'uuid' => '0',
                    'type' => '5',
                    'mid' => $store_id,
                    'version' => 'v1.1.125',
                    'scope' => 'base',
                    'route' => 'plugin.store-cashier.frontend.Order.create',
                    'price' => $price,
                    'store_id' => $store_id,
                    'member_coupon_ids' => $member_coupon_ids,
                    'orders' => $orders,
                    'mobile' => $mobile,
                    'realname' => $realname
                ]);
                $orderRequest->ip = request()->ip();
                $orderRequest->order_id = $order->id;
                $orderRequest->updated_at = time();
                $orderRequest->created_at = time();
                $orderRequest->save();
                
                // 创建订单商品记录
                $orderGoods = new \App\Models\OrderGoods();
                $orderGoods->comment_status = 0;
                $orderGoods->coupon_price = 0;
                $orderGoods->created_at = time();
                $orderGoods->deduction_amount = 0;
                $orderGoods->goods_cost_price = $price;
                $orderGoods->goods_id = $cashier_goods_id;
                $orderGoods->goods_market_price = $price;
                $orderGoods->goods_option_id = 0;
                $orderGoods->goods_option_title = '';
                $orderGoods->goods_price = $price;
                $orderGoods->goods_sn = '';
                $orderGoods->need_address = 0;
                $orderGoods->order_id = $order->id;
                $orderGoods->payment_amount = $price;
                $orderGoods->price = $price;
                $orderGoods->product_sn = '';
                
                // 获取商品图片 - 优先从商品表获取，否则使用门店图片
                $goods = \App\Models\Goods::find($cashier_goods_id);
                $thumb = '';
                if ($goods && $goods->thumb) {
                    $thumb = $goods->thumb;
                } elseif ($store && $store->thumb) {
                    $thumb = $store->thumb;
                }
                $orderGoods->thumb = $thumb;
                
                $orderGoods->title = $store->store_name ?? '收银台';
                $orderGoods->total = 1;
                $orderGoods->uid = $uid;
                $orderGoods->uniacid = 1;
                $orderGoods->updated_at = time();
                $orderGoods->vip_price = $price;
                $orderGoods->save();
                
                // 创建订单创建任务记录
                $orderCreatedJob = new \App\Models\OrderCreatedJob();
                $orderCreatedJob->order_id = $order->id;
                $orderCreatedJob->updated_at = time();
                $orderCreatedJob->created_at = time();
                $orderCreatedJob->save();
                
                // 创建订单合并创建记录
                $orderMergeCreate = new \App\Models\OrderMergeCreate();
                $orderMergeCreate->uniacid = 1;
                $orderMergeCreate->order_ids = (string)$order->id;
                $orderMergeCreate->updated_at = time();
                $orderMergeCreate->created_at = time();
                $orderMergeCreate->save();
                
                return [
                    'order' => $order,
                    'orderGoods' => $orderGoods,
                    'storeOrder' => $storeOrder
                ];
            });
            
            // 按照老项目返回格式
            $responseData = [
                'order_ids' => $result['order']->id,
                'orders' => [
                    [
                        'id' => $result['order']->id,
                        'order_sn' => $result['order']->order_sn,
                        'price' => $result['order']->price,
                        'goods_price' => $result['order']->goods_price,
                        'dispatch_price' => $result['order']->dispatch_price,
                        'discount_price' => $result['order']->discount_price,
                        'deduction_price' => $result['order']->deduction_price,
                        'status' => $result['order']->status,
                        'created_at' => $result['order']->create_time, // 直接使用时间戳
                        'updated_at' => $result['order']->create_time // 直接使用时间戳
                    ]
                ],
                'total_price' => $result['order']->price,
                'goods_price' => $result['order']->goods_price,
                'dispatch_price' => $result['order']->dispatch_price,
                'discount_price' => $result['order']->discount_price,
                'deduction_price' => $result['order']->deduction_price
            ];
            
            return response()->json([
                'result' => 1,
                'msg'    => '订单创建成功',
                'data'   => $responseData
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '创建订单失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 支付订单
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function payOrder(Request $request)
    {
        try {
            $order_ids = $this->getParam($request, 'order_ids', '');
            $pay_type_id = (int) $this->getParam($request, 'pay_type_id', 0);
            
            if (!$order_ids || !$pay_type_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '参数不完整',
                    'data'   => []
                ]);
            }
            
            // 这里应该实现实际的支付逻辑
            // 包括调用第三方支付接口、更新订单状态等
            
            $result = [
                'pay_sn' => 'PAY' . date('YmdHis') . rand(1000, 9999),
                'pay_status' => 1,
                'pay_time' => now()->format('Y-m-d H:i:s')
            ];
            
            return response()->json([
                'result' => 1,
                'msg'    => '支付成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '支付失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 合并支付获取信息
     * 对应老项目的 order.merge-pay 接口
     * 按照老项目 MergePayController::index 方法逻辑实现
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function mergePay(Request $request)
    {
        try {
            $orderIds = $this->getParam($request, 'order_ids', '');
            $pid = $this->getParam($request, 'pid', '');
            
            if (!$orderIds || !$pid) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '参数不完整',
                    'data'   => []
                ]);
            }
            
            // 验证订单ID格式 - 按照老项目逻辑
            if (!is_array($orderIds)) {
                $orderIds = explode(',', $orderIds);
            }
            array_walk($orderIds, function ($orderId) {
                if (!is_numeric($orderId)) {
                    throw new \Exception('(ID:' . $orderId . ')订单号id必须为数字');
                }
            });
            
            // 查询订单信息 - 按照老项目逻辑
            $orders = \App\Models\Order::select(['status', 'id', 'order_sn', 'price', 'uid', 'plugin_id', 'is_pending'])
                ->whereIn('id', $orderIds)
                ->get();
            
            if ($orders->count() != count($orderIds)) {
                throw new \Exception('(ID:' . implode(',', $orderIds) . ')未找到订单');
            }
            
            // 加载订单商品信息
            $orders->load('orderGoods');
            
            // 检查是否为收银台商品（茶包支付） - 按照老项目第74-85行逻辑
            $isTeaBag = false;
            $firstOrder = $orders->first();
            if ($firstOrder && $firstOrder->orderGoods) {
                foreach ($firstOrder->orderGoods as $orderGood) {
                    $storeGoods = \App\Models\StoreGoods::where('goods_id', $orderGood->goods_id)->first();
                    if (!empty($storeGoods)) {
                        $isTeaBag = true;
                        break;
                    }
                }
            }
            
            // 获取用户信息 - 按照老项目逻辑
            if ($isTeaBag) {
                // 收银台商品：从 love_member 表获取茶包余额
                $loveMember = \App\Models\LoveMember::where('member_id', $pid)->first();
                $memberData = [
                    'credit2' => $loveMember ? round((float)$loveMember->usable, 2) : 0.00
                ];
            } else {
                // 普通商品：从 member 表获取余额
                $member = \App\Models\Member::select(['credit2'])->find($pid);
                $memberData = [
                    'credit2' => $member ? round((float)$member->credit2, 2) : 0.00
                ];
            }
            
            // 生成支付记录 - 按照老项目 PreOrderPay 逻辑
            $orderPay = new \App\Models\OrderPay();
            $orderPay->status = 0; // 待支付
            $orderPay->pay_type_id = 0;
            $orderPay->order_ids = $orderIds; // 直接赋值数组，Laravel会自动转为JSON格式
            $orderPay->amount = $orders->sum('price');
            $orderPay->uid = $pid;
            $orderPay->pay_sn = $this->createPaySN(); // 使用老项目的支付号生成逻辑
            $orderPay->created_at = time();
            $orderPay->updated_at = time();
            $orderPay->save();
            
            // 创建订单支付关联记录
            foreach ($orderIds as $orderId) {
                $orderPayOrder = new \App\Models\OrderPayOrder();
                $orderPayOrder->order_id = $orderId;
                $orderPayOrder->order_pay_id = $orderPay->id;
                $orderPayOrder->save();
            }
            
            // 构建支付按钮 - 按照老项目逻辑
            $buttons = [];
            
            if ($isTeaBag) {
                // 收银台商品使用茶包支付 - 按照老项目第109-120行逻辑
                $buttons[] = [
                    'code' => 'MemberCard',
                    'name' => '茶包支付',
                    'value' => 133,
                    'need_password' => false,
                    'weight' => 110,
                ];
            } else {
                // 普通商品支付方式 - 按照老项目 PaymentConfig 逻辑
                $orderPaymentTypes = $this->getOrderPaymentTypes($firstOrder->plugin_id);
                $buttons = $this->buildPaymentButtons($orderPaymentTypes);
                
                // 处理微信小程序支付转换 - 按照老项目第121-135行逻辑
                $new_buttons = [];
                foreach ($buttons as $b) {
                    if ($b['code'] == 'wechatMinPay') {
                        // 小程序支付转换为公众号支付
                        $new_buttons[] = [
                            'code' => 'wechatPay',
                            'name' => $b['name'],
                            'value' => $b['value'],
                            'need_password' => $b['need_password'],
                            'weight' => $b['weight'],
                        ];
                    } else {
                        $new_buttons[] = $b;
                    }
                }
                $buttons = $new_buttons;
            }
            
            // 获取支付跳转URL - 按照老项目第138-142行逻辑
            $minRedirectUrl = '';
            $tradeSetting = \App\Models\Setting::get('shop.trade', []);
            if (isset($tradeSetting['min_redirect_url']) && !empty($tradeSetting['min_redirect_url'])) {
                $minRedirectUrl = $tradeSetting['min_redirect_url'];
            }
            
            // 构建返回数据 - 按照老项目第145-149行格式
            $result = [
                'order_pay' => [
                    'id' => $orderPay->id,
                    'pay_sn' => $orderPay->pay_sn,
                    'amount' => $orderPay->amount,
                    'uid' => $orderPay->uid,
                    'status' => $orderPay->status,
                    'created_at' => $orderPay->created_at,
                    'updated_at' => $orderPay->updated_at
                ],
                'member' => $memberData,
                'buttons' => $buttons,
                'typename' => '',
                'min_redirect_url' => $minRedirectUrl,
                'order_contract' => []
            ];
            
            return response()->json([
                'result' => 1,
                'msg'    => '成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取合并支付信息失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 生成支付流水号 - 按照老项目 OrderService::createPaySN 逻辑
     */
    private function createPaySN()
    {
        $paySN = 'PN' . date('YmdHis') . rand(1000, 9999);
        while (1) {
            if (!\App\Models\OrderPay::where('pay_sn', $paySN)->first()) {
                break;
            }
            $paySN = 'PN' . date('YmdHis') . rand(1000, 9999);
        }
        return $paySN;
    }
    
    /**
     * 获取茶包余额 - 从 love_member 表的 usable 字段获取
     * 
     * @param int $uid 用户ID
     * @return float
     */
    private function getTeaBagBalance($uid)
    {
        $loveMember = \App\Models\LoveMember::where('member_id', $uid)->first();
        return $loveMember ? round((float)$loveMember->usable, 2) : 0.00;
    }
    
    /**
     * 获取订单支付类型
     */
    private function getOrderPaymentTypes($pluginId)
    {
        // 这里需要根据插件ID获取支付类型，暂时返回基础支付方式
        return [
            ['id' => 1, 'name' => '微信支付', 'code' => 'wechatPay'],
            ['id' => 2, 'name' => '支付宝', 'code' => 'alipay'],
            ['id' => 3, 'name' => '余额支付', 'code' => 'balance']
        ];
    }
    
    /**
     * 构建支付按钮
     */
    private function buildPaymentButtons($paymentTypes)
    {
        $buttons = [];
        foreach ($paymentTypes as $type) {
            $buttons[] = [
                'code' => $type['code'],
                'name' => $type['name'],
                'value' => $type['id'],
                'need_password' => false,
                'weight' => $type['id'] * 100,
            ];
        }
        return $buttons;
    }
    
    /**
     * 获取小程序跳转URL - 从 Setting 配置中获取
     * 对应老项目的 Setting::get('shop.trade')['min_redirect_url']
     * 
     * @return string
     */
    private function getMinRedirectUrl()
    {
        $tradeSetting = \App\Models\Setting::get('shop.trade', []);
        return $tradeSetting['min_redirect_url'] ?? '';
    }
    
    /**
     * 语音播报接口
     * 对应老项目的 plugin.store-cashier.frontend.cashier.voice.index 接口
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function voiceIndex(Request $request)
    {
        try {
            $order_pay_id = $this->getParam($request, 'order_pay_id', '');
            
            if (!$order_pay_id) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '参数不完整',
                    'data'   => []
                ]);
            }
            
            // 查询支付记录
            $orderPay = \App\Models\OrderPay::find($order_pay_id);
            if (!$orderPay) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '支付记录不存在',
                    'data'   => []
                ]);
            }
            
            // 查询订单信息（order_ids会自动从JSON转为数组）
            $orderIds = $orderPay->order_ids;
            $orders = \App\Models\Order::whereIn('id', $orderIds)->get();
            
            // 构建语音播报数据
            $voiceData = [
                'order_sn' => $orderPay->pay_sn,
                'amount' => (float)$orderPay->amount,
                'pay_time' => date('Y-m-d H:i:s', (int)$orderPay->created_at),
                'orders' => $orders->map(function($order) {
                    return [
                        'order_sn' => $order->order_sn,
                        'price' => (float)$order->price,
                        'status' => (int)$order->status
                    ];
                })->toArray()
            ];
            
            return response()->json([
                'result' => 1,
                'msg'    => '语音播报数据获取成功',
                'data'   => $voiceData
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '语音播报失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 余额支付
     * 对应老项目的 order.credit-merge-pay.credit2 接口
     * 按照老项目 CreditMergePayController::credit2 方法逻辑实现
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function creditMergePay(Request $request)
    {
        try {
            $orderPayId = $this->getParam($request, 'order_pay_id', '');
            $pid = $this->getParam($request, 'pid', '');
            $isType = $this->getParam($request, 'is_type', 0);
            $payType = $this->getParam($request, 'pay_type', '');
            $paymentPassword = $this->getParam($request, 'payment_password', '');
            $mid = $this->getParam($request, 'mid', '');
            
            if (!$orderPayId || !$pid) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '参数不完整',
                    'data'   => []
                ]);
            }
            
            // 处理支付类型 - 按照老项目逻辑
            if ($payType == '3') {
                $payType = 133; // 茶包支付
            } elseif ($payType == '133') {
                $payType = 133; // 茶包支付
            } elseif ($payType == '137') {
                $payType = 137; // 沐浴露   
            }elseif ($payType == '138') {
                $payType = 138; // 额度   
            }
            
            // 查询支付记录
            $orderPay = \App\Models\OrderPay::find($orderPayId);
            if (!$orderPay) {
                throw new \Exception('支付记录不存在');
            }
            
            // 查询订单信息（order_ids会自动从JSON转为数组）
            $orderIds = $orderPay->order_ids;
            $orders = \App\Models\Order::whereIn('id', $orderIds)->get();
            if ($orders->isEmpty()) {
                throw new \Exception('订单不存在');
            }
            
            // 验证沐浴露余额 - 按照老项目逻辑
            if ($payType == 137) {
                // 先查出设置的支持哪种沐浴露（按pay_sort排序）
                $breedConsumes = \App\Models\BreedConsume::where(['is_swap' => 1])->orderBy('pay_sort')->get();
                $userCoin = 0;
                $user_id = $pid;
                // 算出用户沐浴露是否足够
                foreach ($breedConsumes as $breedConsume) {
                    $record = \App\Models\BreedUserCoin::where(['user_id' => $user_id, 'consume_type' => $breedConsume->id])->first();
                    $num = $record ? round((float)$record->num, 2) : 0;
                    $userCoin = round($userCoin + $num, 2);
                }
                if ($userCoin < $orderPay->amount) {
                    return response()->json([
                        'result' => 0,
                        'msg'    => '沐浴露余额不足',
                        'data'   => []
                    ]);
                }
            }

            $cloudQuotaStoreId = null;
            if ($payType == 138) {
                $coinQuota = \App\Models\BreedUserCoinQuota::where('user_id', $pid)->first();
                $coinQuotaValue = round((float)($coinQuota->num ?? 0), 2);

                if ($coinQuotaValue >= $orderPay->amount) {
                    $cloudStockQuotaValue = 0.0;
                } else {
                    $cloudStockQuotaValue = 0.0;
                    $storeOwner = \App\Models\Store::where('uid', $pid)->first();
                    if ($storeOwner) {
                        $cloudQuotaStoreId = $storeOwner->id;
                        $cloudStockQuotaValue = round((float) (DB::table('ims_hhm_coin_corp_quota')
                            ->where('store_id', $storeOwner->id)
                            ->where('switch', 1)
                            ->where('status', 2)
                            ->where('stock_status', 0)
                            ->value('stock_num') ?? 0), 2);
                    }
                }

                if (($coinQuotaValue + $cloudStockQuotaValue) < $orderPay->amount) {
                    return response()->json([
                        'result' => 0,
                        'msg'    => '额度余额不足；',
                        'data'   => []
                    ]);
                }
            }
            
            // 验证茶包余额 - 按照老项目逻辑
            if ($isType == 1) {
                $loveMember = \App\Models\LoveMember::where('member_id', $pid)->first();
                $loveUsable = $loveMember ? round((float)$loveMember->usable, 2) : 0.0;
                if ($loveUsable < $orderPay->amount) {
                    return response()->json([
                        'result' => 0,
                        'msg'    => '茶包余额不足',
                        'data'   => []
                    ]);
                }
            }
            
            // 使用数据库事务确保数据一致性
            $result = \DB::transaction(function () use ($orderPay, $orders, $pid, $payType, $isType, $mid, $orderPayId, $cloudQuotaStoreId) {
                
                // 获取门店和置换分组信息 - 按照老项目第187-202行逻辑
                $order = $orders->first();
                $orderGoods = \App\Models\OrderGoods::where('order_id', $order->id)->first();
                if (!$orderGoods) {
                    throw new \Exception('订单商品不存在');
                }
                
                $goods_id = $orderGoods->goods_id;
                $store = \App\Models\Store::where('cashier_id', $goods_id)->first();
                if (!$store) {
                    throw new \Exception('门店不存在');
                }
                
                $store_id = $store->id;
                $quotaStoreId = $cloudQuotaStoreId ?: null;
                
                // ===== 插入支付日志记录 - 按照老项目 Pay::log() 方法逻辑 =====
                $payTypeName = $payType == 137 ? '沐浴露' : ($payType == 133 ? '茶包' : ($payType == 138 ? '额度' : '余额'));
                
                // 1. 插入支付日志 (ims_yz_pay_log)
                \App\Models\PayLog::create([
                    'uniacid' => 1,
                    'member_id' => $pid,
                    'type' => 1, // 支付类型：1=订单支付
                    'third_type' => $payTypeName,
                    'price' => $orderPay->amount,
                    'operation' => $payTypeName . '订单支付 订单号：' . $orderPay->pay_sn,
                    'ip' => request()->ip(),
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                
                // 2. 插入支付单记录 (ims_yz_pay_order) - 初始状态为待支付(status=0)
                $payOrder = \App\Models\PayOrder::create([
                    'uniacid' => 1,
                    'member_id' => $pid,
                    'int_order_no' => 'P' . date('Ymd') . strtolower(substr(md5(uniqid() . rand()), 0, 20)),
                    'out_order_no' => $orderPay->pay_sn,
                    'status' => 0, // 初始状态：待支付
                    'type' => 1, // 支付类型：1=订单支付
                    'third_type' => $payTypeName,
                    'price' => $orderPay->amount,
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                
                // 3. 插入请求数据日志 (ims_yz_pay_request_data)
                \App\Models\PayRequestData::create([
                    'uniacid' => 1,
                    'out_order_no' => $orderPay->pay_sn,
                    'type' => 1,
                    'third_type' => $payTypeName,
                    'params' => json_encode([
                        'order_no' => $orderPay->pay_sn,
                        'amount' => (string)$orderPay->amount,
                        'subject' => $store->store_name ?? '收银台',
                        'body' => ($store->store_name ?? '收银台') . ':1',
                        'extra' => ['type' => 1],
                        'member_id' => $pid,
                        'operator' => -1,
                        'operator_id' => $orderPayId,
                        'remark' => '合并支付(id:' . $orderPayId . '),' . $payTypeName . '付款' . $orderPay->amount . '元',
                        'service_type' => 2,
                        'trade_no' => 0
                    ]),
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                
                // 查询门店对应的置换分组属性 - 按照老项目第197-202行
                $storeGroupPropertie = \App\Models\StoreCashierSwitchCodeGroupProperties::select([
                        'ims_yz_store_cashier_switch_code_group_properties.*',
                        'ims_yz_store_cashier_switch_code_group_relation.settlement_num'
                    ])
                    ->leftJoin('ims_yz_store_cashier_switch_code_group_relation',
                        'ims_yz_store_cashier_switch_code_group_relation.group_propertie_id', '=',
                        'ims_yz_store_cashier_switch_code_group_properties.id')
                    ->where('ims_yz_store_cashier_switch_code_group_relation.store_id', $store_id)
                    ->where('ims_yz_store_cashier_switch_code_group_properties.in_type', $payType)
                    // ->where('ims_yz_store_cashier_switch_code_group_relation.state', 1)
                    ->first();
                
                // 如果没有找到置换配置，使用默认配置
                if (!$storeGroupPropertie) {
                    // 使用默认配置：茶包进->茶包出，100%结算
                    $storeGroupPropertie = (object)[
                        'out_type' => 133, // 默认茶包结算
                        'settlement_num' => 100, // 默认100%结算给商家
                        'out_type_attribute' => 6, // 默认沐浴露类型6（int类型）
                        'in_type' => $payType
                    ];
                    
                    \Log::warning('未找到门店置换配置，使用默认配置', [
                        'store_id' => $store_id,
                        'pay_type' => $payType
                    ]);
                }
                
                // 代理分成逻辑 - 改为根据结算资产类型（out_type）
                $this->processRegionAgentCommission($order, $storeGroupPropertie->out_type, $store);
                
                // 根据结算类型处理 - 按照老项目第217-305行逻辑
                if ($storeGroupPropertie->out_type == 137) {
                    // ===== 沐浴露结算 - 按照老项目第217-250行逻辑 =====
                    
                    // 1. 扣减用户余额（按用户选择的支付方式）
                    if ($isType == 1 || $payType == 133) {
                        // 用户选择茶包支付，扣减茶包
                        $this->deductTeaBag($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id);
                    } elseif ($payType == 137) {
                        // 用户选择沐浴露支付，扣减沐浴露
                        $this->deductBreedCoin($pid, $orderPay->amount, $payType, $order->order_sn);
                    } elseif ($payType == 138) {
                        // 用户选择额度支付，扣减额度
                        $this->deductQuota($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id, $store->store_name ?? '', $order->order_sn ?? '', $quotaStoreId);
                    }
                    
                    // 2. 结算给商家沐浴露
                    $this->settlementBreedCoin([
                        'store_uid' => $store->uid,
                        'order_id' => $order->id,
                        'out_type_attribute' => $storeGroupPropertie->out_type_attribute,
                        'settlement_num' => $storeGroupPropertie->settlement_num,
                        'pay_type_id' => $payType,
                        'amount' => $orderPay->amount,
                        'order_sn' => $order->order_sn
                    ]);
                    
                    // 3. 更新订单支付记录状态
                    $orderPay->status = 1; // 已支付
                    $orderPay->pay_type_id = $payType;
                    $orderPay->pay_time = time();
                    $orderPay->updated_at = time();
                    $orderPay->save();
                    
                    // 3.1 更新支付单状态为已支付 - 按照老项目 CreditPay::doPay3 第92-98行
                    $payOrder->status = 2; // 已支付
                    $payOrder->trade_no = $orderPay->pay_sn;
                    $payOrder->third_type = $payTypeName;
                    $payOrder->updated_at = time();
                    $payOrder->save();
                    
                    // 4. 更新订单状态
                    foreach ($orders as $order) {
                        $order->status = 3; // 已完成
                        $order->pay_time = time();
                        $order->send_time = time();
                        $order->pay_type_id = $payType;
                        $order->updated_at = time();
                        $order->save();
                    }
                } elseif ($storeGroupPropertie->out_type == 138) {
                    // ===== 额度结算给商家 =====

                    // 1. 扣减用户余额（按用户选择的支付方式）
                    if ($isType == 1 || $payType == 133) {
                        // 用户选择茶包支付，扣减茶包
                        $this->deductTeaBag($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id);
                    } elseif ($payType == 137) {
                        // 用户选择沐浴露支付，扣减沐浴露
                        $this->deductBreedCoin($pid, $orderPay->amount, $payType, $order->order_sn);
                    } elseif ($payType == 138) {
                        // 用户选择额度支付，扣减额度
                        $this->deductQuota($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id, $store->store_name ?? '', $order->order_sn ?? '', $quotaStoreId);
                    }

                    // 2. 结算给商家额度（根据结算比例计算入账金额）
                    $this->settlementQuota([
                        'store_uid' => $store->uid,
                        'order_id' => $order->id,
                        'settlement_num' => $storeGroupPropertie->settlement_num,
                        'amount' => $orderPay->amount,
                        'order_sn' => $order->order_sn
                    ]);

                    // 3. 更新订单支付记录状态
                    $orderPay->status = 1; // 已支付
                    $orderPay->pay_type_id = $payType;
                    $orderPay->pay_time = time();
                    $orderPay->updated_at = time();
                    $orderPay->save();

                    // 3.1 更新支付单状态为已支付
                    $payOrder->status = 2; // 已支付
                    $payOrder->trade_no = $orderPay->pay_sn;
                    $payOrder->third_type = $payTypeName;
                    $payOrder->updated_at = time();
                    $payOrder->save();

                    // 4. 更新订单状态
                    foreach ($orders as $order) {
                        $order->status = 3; // 已完成
                        $order->pay_time = time();
                        $order->send_time = time();
                        $order->pay_type_id = $payType;
                        $order->updated_at = time();
                        $order->save();
                    }
                } else {
                    // ===== 茶包结算 - 按照老项目第252-305行逻辑 =====
                    
                    $price = $order->price;
                    
                    // 1. 更新收银台订单手续费 - 按照老项目第255-262行
                    $cashierOrder = \App\Models\CashierOrder::where('order_id', $order->id)->first();
                    if ($cashierOrder) {
                        $cashierOrder->fee_percentage = 100 - $storeGroupPropertie->settlement_num;
                        $usercoin = round($price * $storeGroupPropertie->settlement_num / 100, 2);
                        $cashierOrder->fee = round($price - $usercoin, 2);
                        $cashierOrder->amount = $usercoin;
                        $cashierOrder->pay_type_id = $payType;
                        $cashierOrder->updated_at = time();
                        $cashierOrder->save();
                    }
                    
                    // 2. 扣减用户余额
                    if ($isType == 1 || $payType == 133) {
                        // 扣减茶包余额
                        $this->deductTeaBag($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id);
                    } elseif ($payType == 137) {
                        // 扣减沐浴露余额
                        $this->deductBreedCoin($pid, $orderPay->amount, $payType, $order->order_sn);
                    } elseif ($payType == 138) {
                        // 扣减额度余额
                        $this->deductQuota($pid, $orderPay->amount, $orderPay->pay_sn, $orderPay->id, $store->store_name ?? '', $order->order_sn ?? '', $quotaStoreId);
                    }

                    // 2.1 结算给商家茶包（根据结算比例计算入账金额）
                    $settlementAmount = round($price * $storeGroupPropertie->settlement_num / 100, 2);
                    if ($settlementAmount > 0) {
                        $this->settlementTeaBag([
                            'store_uid' => $store->uid,
                            'order_id' => $order->id,
                            'settlement_amount' => $settlementAmount,
                            'order_sn' => $order->order_sn
                        ]);
                    }
                    
                    // 3. 更新订单支付记录状态 - 按照老项目第272行
                    $orderPay->status = 1; // 已支付
                    $orderPay->pay_type_id = $payType;
                    $orderPay->pay_time = time();
                    $orderPay->updated_at = time();
                    $orderPay->save();
                    
                    // 3.1 更新支付单状态为已支付 - 按照老项目 CreditPay::doPay 第128-135行
                    $payOrder->status = 2; // 已支付
                    $payOrder->trade_no = $orderPay->pay_sn;
                    $payOrder->third_type = $payTypeName;
                    $payOrder->updated_at = time();
                    $payOrder->save();
                    
                    // 4. 更新订单状态
                    foreach ($orders as $order) {
                        $order->status = 3; // 已完成
                        $order->pay_time = time();
                        $order->send_time = time();
                        $order->pay_type_id = $payType;
                        $order->updated_at = time();
                        $order->save();
                    }
                }
                //判断店家云仓额度是否到期，到期后需要自动还款
                if ($store && $store->uid) {
                    CropQuotaService::coinReturn($store->uid,$storeGroupPropertie->out_type);
                }
                
                // 获取跳转URL - 按照老项目第278-293行逻辑
                $redirect = '';
                $tradeSetting = \App\Models\Setting::get('shop.trade', []);
                if (isset($tradeSetting['redirect_url']) && !empty($tradeSetting['redirect_url'])) {
                    $redirect = $tradeSetting['redirect_url'] . '&outtradeno=' . $orderPayId;
                }
                
                return [
                    'redirect' => $redirect,
                    'pay_status' => 1,
                    'pay_time' => time()
                ];
            });
            
            return response()->json([
                'result' => 1,
                'msg'    => '成功',
                'data'   => $result
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '支付失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 【临时接口】创建门店置换配置
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function createStoreSwapConfig(Request $request)
    {
        try {
            $storeId = (int)$this->getParam($request, 'store_id', 0);
            $inType = (int)$this->getParam($request, 'in_type', 133); // 133=茶包, 137=沐浴露
            $outType = (int)$this->getParam($request, 'out_type', 133); // 结算类型
            $settlementNum = (float)$this->getParam($request, 'settlement_num', 100); // 结算比例
            
            if (!$storeId) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '门店ID不能为空',
                    'data'   => []
                ]);
            }
            
            \DB::transaction(function () use ($storeId, $inType, $outType, $settlementNum) {
                // 1. 创建或查找分组属性
                $groupPropertie = \App\Models\StoreCashierSwitchCodeGroupProperties::firstOrCreate(
                    ['in_type' => $inType],
                    [
                        'uniacid' => 1,
                        'in_type' => $inType,
                        'out_type' => $outType,
                        'out_type_attribute' => 6, // 沐浴露类型6（int类型）
                        'created_at' => time(),
                        'updated_at' => time()
                    ]
                );
                
                // 2. 创建或更新门店与分组的关联
                $relation = \App\Models\StoreCashierSwitchCodeGroupRelation::where([
                    'store_id' => $storeId,
                    'group_propertie_id' => $groupPropertie->id
                ])->first();
                
                if ($relation) {
                    $relation->settlement_num = $settlementNum;
                    $relation->state = 1;
                    $relation->updated_at = time();
                    $relation->save();
                } else {
                    \App\Models\StoreCashierSwitchCodeGroupRelation::create([
                        'uniacid' => 1,
                        'store_id' => $storeId,
                        'group_propertie_id' => $groupPropertie->id,
                        'settlement_num' => $settlementNum,
                        'state' => 1,
                        'created_at' => time(),
                        'updated_at' => time()
                    ]);
                }
            });
            
            return response()->json([
                'result' => 1,
                'msg'    => '配置创建成功',
                'data'   => [
                    'store_id' => $storeId,
                    'in_type' => $inType,
                    'out_type' => $outType,
                    'settlement_num' => $settlementNum
                ]
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '创建配置失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 【临时接口】充值沐浴露余额
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function rechargeBreedCoin(Request $request)
    {
        try {
            $uid = $this->getParam($request, 'uid', 0);
            $amount = round((float)$this->getParam($request, 'amount', 100), 2);
            $consumeType = (int)$this->getParam($request, 'consume_type', 6); // 默认类型6
            
            if (!$uid) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '用户ID不能为空',
                    'data'   => []
                ]);
            }
            
            // 查找或创建记录
            $breedUserCoin = \App\Models\BreedUserCoin::where('user_id', $uid)
                ->where('consume_type', $consumeType)
                ->first();
            
            if ($breedUserCoin) {
                // 更新余额
                $oldNum = round((float)$breedUserCoin->num, 2);
                $breedUserCoin->num = $amount;
                $breedUserCoin->updated_at = time();
                $breedUserCoin->save();
                
                return response()->json([
                    'result' => 1,
                    'msg'    => '充值成功',
                    'data'   => [
                        'user_id' => $uid,
                        'consume_type' => $consumeType,
                        'old_num' => $oldNum,
                        'new_num' => $amount
                    ]
                ]);
            } else {
                // 创建新记录
                $breedUserCoin = new \App\Models\BreedUserCoin();
                $breedUserCoin->uniacid = 1;
                $breedUserCoin->user_id = $uid;
                $breedUserCoin->num = $amount;
                $breedUserCoin->consume_type = $consumeType;
                $breedUserCoin->created_at = time();
                $breedUserCoin->updated_at = time();
                $breedUserCoin->save();
                
                return response()->json([
                    'result' => 1,
                    'msg'    => '充值成功（新建记录）',
                    'data'   => [
                        'user_id' => $uid,
                        'consume_type' => $consumeType,
                        'num' => $amount
                    ]
                ]);
            }
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '充值失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 【临时接口】充值茶包余额
     * 
     * @param Request $request
     * @return JsonResponse
     */
    public function rechargeTeaBag(Request $request)
    {
        try {
            $uid = $this->getParam($request, 'uid', 0);
            $amount = round((float)$this->getParam($request, 'amount', 100), 2);
            
            if (!$uid) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '用户ID不能为空',
                    'data'   => []
                ]);
            }
            
            // 查找或创建记录
            $loveMember = \App\Models\LoveMember::where('member_id', $uid)->first();
            
            if ($loveMember) {
                // 更新余额
                $oldUsable = round((float)$loveMember->usable, 2);
                $loveMember->usable = $amount;
                $loveMember->updated_at = time();
                $loveMember->save();
                
                return response()->json([
                    'result' => 1,
                    'msg'    => '充值成功',
                    'data'   => [
                        'member_id' => $uid,
                        'old_usable' => $oldUsable,
                        'new_usable' => $amount
                    ]
                ]);
            } else {
                // 创建新记录
                $loveMember = new \App\Models\LoveMember();
                $loveMember->uniacid = 1;
                $loveMember->member_id = $uid;
                $loveMember->usable = $amount;
                $loveMember->created_at = time();
                $loveMember->updated_at = time();
                $loveMember->save();
                
                return response()->json([
                    'result' => 1,
                    'msg'    => '充值成功（新建记录）',
                    'data'   => [
                        'member_id' => $uid,
                        'usable' => $amount
                    ]
                ]);
            }
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '充值失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }
    
    /**
     * 获取语音播报设置
     * 对应老项目的 getVoiceSet 方法
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getVoiceSet(Request $request)
    {
        try {
            $orderIds = $this->getParam($request, 'order_ids', '');
            
            if (!$orderIds) {
                return response()->json([
                    'result' => 0,
                    'msg'    => '订单ID不能为空',
                    'data'   => []
                ]);
            }
            
            // 检查是否开启语音播报
            $voiceEnabled = $this->checkVoiceEnabled();
            
            if ($voiceEnabled) {
                $voiceUrl = $this->generateVoiceUrl($orderIds);
                return response()->json([
                    'result' => 1,
                    'msg'    => '获取语音设置成功',
                    'data'   => ['url' => $voiceUrl]
                ]);
            } else {
                return response()->json([
                    'result' => 0,
                    'msg'    => '语音播报未开启',
                    'data'   => []
                ]);
            }
            
        } catch (\Exception $e) {
            return response()->json([
                'result' => 0,
                'msg'    => '获取语音设置失败: ' . $e->getMessage(),
                'data'   => []
            ]);
        }
    }

    /**
     * 调用马粮API
     *
     * @param string $token
     * @param array $data
     * @return int
     */
    private function callPmApi($token, $data)
    {
        // 这里应该实现实际的马粮API调用
        // 模拟返回平台订单号
        return rand(100000, 999999);
    }

    /**
     * 检查语音播报是否开启
     *
     * @return bool
     */
    private function checkVoiceEnabled()
    {
        // 这里应该检查系统设置
        return true; // 模拟开启
    }

    /**
     * 生成语音URL
     *
     * @param string $orderIds
     * @return string
     */
    private function generateVoiceUrl($orderIds)
    {
        // 这里应该生成实际的语音文件URL
        return 'https://example.com/voice/' . $orderIds . '.mp3';
    }

    /**
     * 获取置换类型列表
     *
     * @param int $store_id
     * @return array
     */
    private function getSwapTypes($store_id)
    {
        try {
            // 这里需要根据实际的置换类型配置来实现
            // 提供一个基础的置换类型列表
            $swapTypes = [
                [
                    'id' => 1,
                    'name' => '积分置换',
                    'code' => 'points',
                    'description' => '使用积分进行置换',
                    'enabled' => true,
                    'sort' => 1
                ],
                [
                    'id' => 2,
                    'name' => '余额置换',
                    'code' => 'balance',
                    'description' => '使用余额进行置换',
                    'enabled' => true,
                    'sort' => 2
                ],
                [
                    'id' => 3,
                    'name' => '优惠券置换',
                    'code' => 'coupon',
                    'description' => '使用优惠券进行置换',
                    'enabled' => true,
                    'sort' => 3
                ]
            ];
            
            // 根据门店配置过滤置换类型
            // 这里可以根据实际需求添加门店特定的置换类型配置逻辑
            
            return $swapTypes;
            
        } catch (\Exception $e) {
            return [
                [
                    'id' => 1,
                    'name' => '积分置换',
                    'code' => 'points',
                    'description' => '使用积分进行置换',
                    'enabled' => true,
                    'sort' => 1
                ]
            ];
        }
    }

    /**
     * 获取基础信息 - 复制老项目的 BasicInformation 中间件逻辑
     *
     * @param Request $request
     * @return array
     */
    private function getBasicInfo($request)
    {
        return [
            'popularize_page' => [
                'wechat' => ['vue_route' => [], 'url' => ''],
                'mini' => ['vue_route' => [], 'url' => '', 'mini_url' => ''],
                'wap' => ['vue_route' => [], 'url' => ''],
                'app' => ['vue_route' => [], 'url' => ''],
                'alipay' => ['vue_route' => [], 'url' => ''],
                'baidu' => null
            ],
            'balance' => '余额',
            'point' => '积分',
            'integral' => '沐浴露',
            'love' => '消费励',
            'lang' => $this->getLangSetting(),
            'globalParameter' => $this->getGlobalParameter(),
            'plugin_setting' => [
                'wechat_notice' => ['enable' => false]
            ],
            'consolidated_payment' => '1',
            'home' => $this->getPublicData()
        ];
    }

    /**
     * 获取验证页面信息
     *
     * @param Request $request
     * @return array
     */
    private function getValidatePage($request)
    {
        return [
            'is_bind_mobile' => 0,
            'invite_page' => 0,
            'is_invite' => 1,
            'is_login' => 1,
            'invite_mobile' => 1
        ];
    }

    /**
     * 获取语言设置
     *
     * @return array
     */
    private function getLangSetting()
    {
        return [
            'test' => [],
            'commission' => [
                'title' => '',
                'commission' => '',
                'agent' => '',
                'level_name' => '',
                'commission_order' => '',
                'commission_amount' => ''
            ],
            'single_return' => [
                'title' => '',
                'single_return' => '',
                'return_name' => '',
                'return_queue' => '',
                'return_log' => '',
                'return_detail' => '',
                'return_amount' => ''
            ],
            'team_return' => [
                'title' => '',
                'team_return' => '',
                'return_name' => '',
                'team_level' => '',
                'return_log' => '',
                'return_detail' => '',
                'return_amount' => '',
                'return_rate' => '',
                'team_name' => '',
                'return_time' => ''
            ],
            'full_return' => [
                'title' => '',
                'full_return' => '',
                'return_name' => '',
                'full_return_log' => '',
                'return_detail' => '',
                'return_amount' => ''
            ],
            'team_dividend' => [
                'title' => '',
                'team_dividend' => '',
                'team_agent_centre' => '',
                'dividend' => '',
                'flat_prize' => '',
                'award_gratitude' => '',
                'dividend_amount' => '',
                'my_agent' => ''
            ],
            'area_dividend' => [
                'area_dividend_center' => '',
                'area_dividend' => '',
                'dividend_amount' => ''
            ],
            'income' => [
                'name_of_withdrawal' => '提现',
                'income_name' => '收入',
                'poundage_name' => '手续费',
                'special_service_tax' => '劳务税',
                'manual_withdrawal' => '手动提现'
            ],
            'agent' => [
                'agent' => '',
                'agent_num' => '',
                'agent_count' => '',
                'agent_order' => '',
                'agent_order_count' => '',
                'agent_goods_num' => ''
            ],
            'merchant' => [
                'title' => '招商',
                'merchant_people' => '招商员',
                'merchant_center' => '招商中心',
                'merchant_reward' => '分红'
            ],
            'appointment' => [
                'project' => '项目',
                'service' => '服务',
                'worker' => '技师'
            ],
            'reserve_simple' => [
                'service' => '服务',
                'reserve_obj' => '预约人员'
            ],
            'store_projects' => [
                'project' => '项目'
            ],
            'plugin_language' => [
                'en' => [
                    'home' => [
                        '输入关键词搜索' => '输入关键词搜索',
                        '品牌优选' => '品牌优选',
                        '限时优惠' => '限时优惠',
                        '用最低价格买好物' => '用最低价格买好物',
                        '限时价' => '限时价',
                        '人气推荐' => '人气推荐',
                        '精选最适合您的商品' => '精选最适合您的商品',
                        '推荐商品' => '推荐商品'
                    ],
                    'category' => [
                        '搜索商品' => '搜索商品',
                        '未检测到子分类数据' => '未检测到子分类数据',
                        '选择分类' => '选择分类',
                        '三级分类' => '三级分类',
                        '暂无其他分类' => '暂无其他分类',
                        '已售' => '已售',
                        '选规格' => '选规格',
                        '去租赁' => '去租赁',
                        '推荐品牌' => '推荐品牌',
                        '推荐分类' => '推荐分类',
                        '加入购物车' => '加入购物车'
                    ],
                    'extension' => [
                        '会员' => '会员',
                        '分享' => '分享',
                        '累计' => '累计',
                        '可' => '可',
                        '去' => '去',
                        '日自动' => '日自动',
                        '领取收益' => '领取收益',
                        '明细' => '明细',
                        '营业额' => '营业额',
                        '权限' => '权限',
                        '更多权限' => '更多权限'
                    ],
                    'cart' => [
                        '购物车' => '购物车',
                        '编辑' => '编辑',
                        '完成' => '完成',
                        '不含运费' => '不含运费',
                        '合计' => '合计',
                        '结算' => '结算',
                        '删除' => '删除',
                        '购物车快饿扁了' => '购物车快饿扁了',
                        '主人快去找点东西吧' => '主人快去找点东西吧',
                        '个人中心' => '个人中心',
                        '去逛逛' => '去逛逛'
                    ],
                    'member' => [
                        '退出登录' => '退出登录',
                        '邀请码' => '邀请码',
                        '复制' => '复制',
                        '实用工具' => '实用工具',
                        '收藏' => '收藏',
                        '足迹' => '足迹',
                        '地址管理' => '地址管理',
                        '设置' => '设置',
                        '消息通知' => '消息通知',
                        '商家管理' => '商家管理',
                        '营销互动' => '营销互动',
                        '二维码' => '二维码',
                        '评论' => '评论',
                        '客户' => '客户',
                        '优惠券' => '优惠券',
                        '资产权益' => '资产权益',
                        '二维码生成中 请稍候查看' => '二维码生成中 请稍候查看'
                    ],
                    '我的推广' => '我的推广',
                    '分类' => '分类',
                    '会员中心' => '会员中心',
                    '预估收益' => '预估收益',
                    '天' => '天',
                    '搜索' => '搜索',
                    '加载更多' => '加载更多',
                    '没有更多了' => '没有更多了',
                    'money' => '¥',
                    '元' => '元',
                    '全选' => '全选',
                    '下架' => '下架',
                    '售罄' => '售罄',
                    '已下架' => '已下架',
                    '不存在' => '不存在',
                    '失效' => '失效'
                ]
            ]
        ];
    }

    /**
     * 获取全局参数
     *
     * @return array
     */
    private function getGlobalParameter()
    {
        return [
            'is_open_delivery_station' => 0,
            'is_open_photo_order' => 0,
            'delivery_driver_open' => 0,
            'is_open_package_deliver' => '1',
            'assemble_name' => '安装服务',
            'assemble_worker_name' => '安装师傅',
            'consume_red_packet_status' => 0,
            'is_open_shop_esign' => 0,
            'ios_virtual_pay' => 0,
            'order_locate' => false,
            'register_locate' => false,
            'bind_mobile_locate' => false,
            'vip_show' => false,
            'invest_people_name' => '招商专员',
            'invest_people_open' => true,
            'cart_num' => 1,
            'crm_account_bind' => 0
        ];
    }

    /**
     * 获取用户茶包与沐浴露余额
     * 返回：tea_bag 可用茶包；breed_coin 可用沐浴露（支持置换的类型总和）
     */
    public function getUserBalances(Request $request)
    {
        try {
            $uid = (int) $this->getParam($request, 'uid', 0);
            if (!$uid) {
                $uid = (int) $this->getParam($request, 'user_id', 0);
            }
            if (!$uid) {
                return response()->json([
                    'result'  => 0,
                    'msg'     => '用户ID不能为空',
                    'code'    => 400,
                    'message' => '用户ID不能为空',
                    'data'    => []
                ]);
            }

            // 茶包余额（love_member.usable）
            $loveMember = \App\Models\LoveMember::where('member_id', $uid)->first();
            $teaBag = round((float) ($loveMember->usable ?? 0), 2);

            // 沐浴露余额（支持置换的类型汇总，按pay_sort排序）
            $breedConsumes = \App\Models\BreedConsume::where(['is_swap' => 1])->orderBy('pay_sort')->get();
            $breedCoin = 0.0;
            foreach ($breedConsumes as $consume) {
                $record = \App\Models\BreedUserCoin::where([
                    'user_id' => $uid,
                    'consume_type' => $consume->id
                ])->first();
                $breedCoin = round($breedCoin + (float) ($record->num ?? 0), 2);
            }

            // 授信额度
            $quotaNum = DB::table('ims_yz_breed_user_coin_quota')
                ->where('user_id', $uid)
                ->value('num');
            $quota = round((float) ($quotaNum ?? 0), 2);

            // 云仓库存额度
            $cloudStockQuota = 0.0;
            $store = \App\Models\Store::where('uid', $uid)->first();
            if ($store) {
                $stockNum = DB::table('ims_hhm_coin_corp_quota')
                    ->where('store_id', $store->id)
                    ->where('switch', 1)
                    ->where('status', 2)
                    ->where('stock_status', 0)
                    ->value('stock_num');
                if ($stockNum !== null) {
                    $cloudStockQuota = round((float) $stockNum, 2);
                }
            }

            $coinQuota = round($quota + $cloudStockQuota, 2);

            return response()->json([
                'result'  => 1,
                'msg'     => '成功',
                'code'    => 200,
                'message' => '成功',
                'data'    => [
                    'tea_bag'             => $teaBag,
                    'breed_coin'          => $breedCoin,
                    'quota'               => $quota,
                    'cloud_stock_quota'   => $cloudStockQuota,
                    'coin_quota'          => $coinQuota,
                    'tea_bag_balance'     => $teaBag,
                    'shower_gel_balance'  => $breedCoin,
                    'credit_ring_balance' => $coinQuota,
                    'user_id'             => $uid,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'result'  => 0,
                'msg'     => '获取失败: ' . $e->getMessage(),
                'code'    => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data'    => []
            ]);
        }
    }

    /**
     * 按比例计算金额 - 对应老项目的 proportionMath 全局函数
     * 
     * @param float $baseAmount 基础金额
     * @param float $proportion 比例（百分比）
     * @return float
     */
    private function proportionMath($baseAmount, $proportion)
    {
        if ($proportion <= 0) {
            return 0;
        }
        // 计算：基础金额 * 比例 / 100，保留两位小数
        $result = ($baseAmount * $proportion) / 100;
        return round($result, 2);
    }
    
    /**
     * 扣减茶包余额
     * 对应老项目的 LoveChangeService::deduction
     * 
     * @param int $memberId 会员ID
     * @param float $amount 扣减金额
     * @param string $paySn 支付单号
     * @param int $orderPayId 支付记录ID
     * @return void
     */
    private function deductTeaBag($memberId, $amount, $paySn, $orderPayId)
    {
        $loveMember = \App\Models\LoveMember::where('member_id', $memberId)->first();
        $oldLoveUsable = $loveMember ? round((float)$loveMember->usable, 2) : 0.0;
        $newLoveUsable = round(max(0, $oldLoveUsable - (float)$amount), 2);

        // 创建爱心值变化记录
        $love = new \App\Models\Love();
        $love->uniacid = 1;
        $love->member_id = $memberId;
        $love->old_value = $oldLoveUsable;
        $love->change_value = round(-$amount, 2);
        $love->new_value = $newLoveUsable;
        $love->type = 2; // 减少
        $love->source = 4; // 消费
        $love->relation = $paySn;
        $love->operator = 2;
        $love->operator_id = $orderPayId;
        $love->remark = '消费减少';
        $love->value_type = 1;
        $love->created_at = time();
        $love->updated_at = time();
        $love->save();
        
        // 更新用户茶包余额
        if ($loveMember) {
            $loveMember->usable = $newLoveUsable;
            $loveMember->updated_at = time();
            $loveMember->save();
        } else {
            // 如无记录则创建一条
            $loveMember = new \App\Models\LoveMember();
            $loveMember->uniacid = 1;
            $loveMember->member_id = $memberId;
            $loveMember->usable = $newLoveUsable;
            $loveMember->updated_at = time();
            $loveMember->created_at = time();
            $loveMember->save();
        }
    }
    
    /**
     * 扣减沐浴露余额
     * 对应老项目的 BreedChangeService::deduction
     * 
     * @param int $userId 用户ID
     * @param float $amount 扣减金额
     * @param int $payTypeId 支付类型ID
     * @param string $orderSn 订单号
     * @return void
     */
    private function deductBreedCoin($userId, $amount, $payTypeId, $orderSn)
    {
        // 查找支持置换的沐浴露类型（按pay_sort排序，优先扣减排序值小的）
        $breedConsumes = \App\Models\BreedConsume::where(['is_swap' => 1])->orderBy('pay_sort')->get();
        
        $remainingAmount = round((float)$amount, 2);
        
        foreach ($breedConsumes as $breedConsume) {
            if ($remainingAmount <= 0) {
                break;
            }
            
            $breedUserCoin = \App\Models\BreedUserCoin::where([
                'user_id' => $userId,
                'consume_type' => $breedConsume->id
            ])->first();
            
            if ($breedUserCoin && $breedUserCoin->num > 0) {
                $oldNum = round((float)$breedUserCoin->num, 2);
                $deductAmount = round(min($oldNum, $remainingAmount), 2);
                $newNum = round($oldNum - $deductAmount, 2);
                
                // 更新余额
                $breedUserCoin->num = $newNum;
                $breedUserCoin->updated_at = time();
                $breedUserCoin->save();
                
                // 创建流水记录
                $breedCoinFlow = new \App\Models\BreedCoinFlow();
                $breedCoinFlow->uniacid = 1;
                $breedCoinFlow->send_user = $userId;
                $breedCoinFlow->rec_user = 0;
                $breedCoinFlow->num = $deductAmount;
                $breedCoinFlow->type = 11; // 消费扣减
                $breedCoinFlow->consume_type = $breedConsume->id;
                $breedCoinFlow->old_coin = $oldNum;
                $breedCoinFlow->new_coin = $newNum;
                $breedCoinFlow->remark = '置换消费,订单号:' . $orderSn;
                $breedCoinFlow->created_at = time();
                $breedCoinFlow->updated_at = time();
                $breedCoinFlow->save();
                
                $remainingAmount = round($remainingAmount - $deductAmount, 2);
            }
        }
    }

    /**
     * 扣减额度余额
     * 使用 ims_yz_breed_user_coin_quota 表，保证在事务内扣减
     * 
     * @param int $userId 用户ID
     * @param float $amount 扣减金额
     * @param string $paySn 支付单号
     * @param int $orderPayId 支付记录ID
     * @return void
     */
    private function deductQuota($userId, $amount, $paySn, $orderPayId, $storeName = null, $orderSn = null, $cloudQuotaStoreId = null)
    {
        $amount = round((float)$amount, 2);
        if ($amount <= 0) {
            return;
        }

        // 加锁读取当前额度
        $record = \DB::table('ims_yz_breed_user_coin_quota')
            ->where('user_id', $userId)
            ->lockForUpdate()
            ->first();

        $oldNum = $record ? round((float)$record->num, 2) : 0.0;
        $deductFromQuota = round(min($oldNum, $amount), 2);
        $remaining = round($amount - $deductFromQuota, 2);

        if ($record) {
            $newNum = round($oldNum - $deductFromQuota, 2);
            \DB::table('ims_yz_breed_user_coin_quota')
                ->where('user_id', $userId)
                ->update([
                    'num' => $newNum,
                    'updated_at' => time()
                ]);

            if ($deductFromQuota > 0) {
                $remark = ($storeName ? ('【' . $storeName . '】') : '') . '置换订单消费，订单号' . ($orderSn ?: $paySn);
                \DB::table('ims_yz_breed_coin_quota_flows')->insert([
                    'send_user' => $userId,
                    'rec_user' => 0,
                    'num' => $deductFromQuota,
                    'uniacid' => 1,
                    'created_at' => time(),
                    'updated_at' => time(),
                    'remark' => $remark,
                    'old_coin' => $oldNum,
                    'new_coin' => $newNum,
                    'type' => 1 // 1-用户支付额度
                ]);
            }
        } elseif ($remaining <= 0) {
            return;
        }

        if ($remaining > 0) {
            if (!$cloudQuotaStoreId) {
                throw new \Exception('额度余额不足。');
            }

            $cloudRecord = \DB::table('ims_hhm_coin_corp_quota')
                ->where('store_id', $cloudQuotaStoreId)
                ->where('switch', 1)
                ->where('status', 2)
                ->where('stock_status', 0)
                ->lockForUpdate()
                ->first();

            if (!$cloudRecord) {
                throw new \Exception('云仓库存额度不足');
            }

            $cloudOld = round((float)($cloudRecord->stock_num ?? 0), 2);
            if ($cloudOld < $remaining) {
                throw new \Exception('云仓库存额度不足');
            }

            $cloudNew = round($cloudOld - $remaining, 2);
            \DB::table('ims_hhm_coin_corp_quota')
                ->where('id', $cloudRecord->id)
                ->update([
                    'stock_num' => $cloudNew,
                    'updated_at' => time()
                ]);

            $cloudRemark = ($storeName ? ('【' . $storeName . '】') : '') . '置换订单支付，订单号' . ($orderSn ?: $paySn);
            \DB::table('ims_hhm_coin_corp_quota_flows')->insert([
                'send_user' => $userId,
                'rec_user' => 0,
                'num' => $remaining,
                'uniacid' => 1,
                'created_at' => time(),
                'updated_at' => time(),
                'remark' => $cloudRemark,
                'old_coin' => $cloudOld,
                'new_coin' => $cloudNew,
                'type' => 1
            ]);
        }
    }
    
    /**
     * 处理区域代理分成
     * 对应老项目的 regionAgent 方法
     * 
     * @param object $order 订单对象
     * @param int $payType 支付类型
     * @param object $store 门店对象
     * @return void
     */
    private function processRegionAgentCommission($order, $payType, $store)
    {

        //结算的时候不管支付方式，结算类型是什么，都结算c款沐浴露。
        $payType=137;
        try {
            // 查询代理分成配置 - 按照老项目第205-210行
            if ($payType == 137) {
                // 沐浴露支付的分成配置
                $config = \App\Models\DistrictAgentCommissionConfig::where('id', 1)->first();
            } elseif ($payType == 133) {
                // 茶包支付的分成配置
                $config = \App\Models\DistrictAgentCommissionConfig::where('id', 2)->first();
            } else {
                return; // 其他支付类型不处理
            }
            
            if (!$config) {
                \Log::info('未找到代理分成配置，跳过分成处理', [
                    'pay_type' => $payType
                ]);
                return; // 没有配置则跳过
            }
            
            // 执行代理分成 - 按照老项目第213行
            $this->regionAgent($order, $payType, $store, $config);
            
        } catch (\Exception $e) {
            // 代理分成失败不影响主流程，只记录日志
            \Log::error('代理分成处理失败', [
                'order_id' => $order->id,
                'pay_type' => $payType,
                'error' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 区域代理分成逻辑
     * 对应老项目的 regionAgent 静态方法（第414-482行）
     * 
     * @param object $order 订单
     * @param int $payType 支付类型
     * @param object $store 门店
     * @param object $config 分成配置
     * @return void
     */
    private function regionAgent($order, $payType, $store, $config)
    {
        // 计算分成系数 - 按照老项目第430-436行
        $fee = 1;
        if (isset($config->is_discount) && $config->is_discount == 1) {
            $fee = $fee * $config->discount_percentage / 100;
        }
        if (isset($config->is_pv) && $config->is_pv == 1) {
            $fee = $fee * $config->pv_percentage / 100;
        }
        
        // 计算各级代理的分成比例 - 按照老项目第437-444行
        $pAgentFee = ($config->province_agent_commission ?? 0) * $fee / 100; // 省代
        $cAgentFee = ($config->city_agent_commission ?? 0) * $fee / 100; // 市代
        $dAgentFee = ($config->district_agent_commission ?? 0) * $fee / 100; // 区代
        $pRecruiterFee = ($config->province_recruiter_commission ?? 0) * $fee / 100; // 省招
        $cRecruiterFee = ($config->city_recruiter_commission ?? 0) * $fee / 100; // 市招
        $dRecruiterFee = ($config->district_recruiter_commission ?? 0) * $fee / 100; // 区招
        $referrerFee = ($config->merchant_referrer_commission ?? 0) * $fee / 100; // 门店推荐人
        $groupFee = ($config->county_group_percent ?? 0) * $fee / 100; // 组代理
        $merchantFee = ($config->merchant_commission_percentage ?? 0) * $fee / 100; // 商家
        
        // 如果所有分成都为0，跳过处理
        if ($pAgentFee == 0 && $cAgentFee == 0 && $dAgentFee == 0 && 
            $pRecruiterFee == 0 && $cRecruiterFee == 0 && $dRecruiterFee == 0 && 
            $referrerFee == 0 && $groupFee == 0 && $merchantFee == 0) {
            return;
        }
        
        // 查询各级代理信息 - 按照老项目第446-461行
        try {
            // 查询省代理 - 第446-454行
            $provinceAgent = \App\Models\RegionProvinceAgent::select('ims_yz_region_province_agent.*')
                ->where('province_id', $store->province_id)
                ->join('ims_yz_region_agent', 'ims_yz_region_province_agent.region_id', '=', 'ims_yz_region_agent.id')
                ->where('ims_yz_region_agent.levelId', 8)
                ->first();
            
            $pagent_id = $provinceAgent ? $provinceAgent->agent_id : null;
            $precruiter_id = $provinceAgent ? $provinceAgent->recruiter_id : null;
            
            // 查询市代理 - 第455-457行
            $cityAgent = \App\Models\RegionCityAgent::where([
                'city_id' => $store->city_id,
                'levelId' => 8
            ])->first();
            
            $cagent_id = $cityAgent ? $cityAgent->agent_id : null;
            $crecruiter_id = $cityAgent ? $cityAgent->recruiter_id : null;
            
            // 查询区代理 - 第458-460行
            $districtAgent = \App\Models\RegionCityDistrictAgent::where([
                'district_id' => $store->district_id,
                'levelId' => 8
            ])->first();
            
            $dagent_id = $districtAgent ? $districtAgent->agent_id : null;
            $drecruiter_id = $districtAgent ? $districtAgent->recruiter_id : null;
            
            // 门店推荐人 - 第461行
            $recruiter_id = $store->recruiter_id;
            
            // 商家提成 - 第462-466行
            if (isset($config->is_merchant_commission) && $config->is_merchant_commission == 1) {
                $merchant_id = $store->uid;
                $this->agentBill($payType, $merchantFee, $merchant_id, $store->id, 12, $order->id);
            }
            
            // 查询组代理 - 第467-472行
            $sdistrict_id = $store->district_id;
            $countyGroup = \App\Models\CountyGroup::where('levelId', 8)
                ->where(function ($query) use ($sdistrict_id) {
                    $query->where('counties', 'like', '%' . $sdistrict_id . '%');
                })
                ->first();
            
            $groupAgent_id = $countyGroup ? $countyGroup->agent_id : null;
            $groupRecruiter_id = $countyGroup ? $countyGroup->recruiter_id : null;
            
            // 执行分账 - 按照老项目第473-481行
            $this->agentBill($payType, $pAgentFee, $pagent_id, $store->id, 1, $order->id); // 省代
            $this->agentBill($payType, $cAgentFee, $cagent_id, $store->id, 2, $order->id); // 市代
            $this->agentBill($payType, $dAgentFee, $dagent_id, $store->id, 3, $order->id); // 区代
            $this->agentBill($payType, $pRecruiterFee, $precruiter_id, $store->id, 4, $order->id, $pagent_id); // 省招
            $this->agentBill($payType, $cRecruiterFee, $crecruiter_id, $store->id, 5, $order->id, $cagent_id); // 市招
            $this->agentBill($payType, $dRecruiterFee, $drecruiter_id, $store->id, 6, $order->id, $dagent_id); // 区招
            $this->agentBill($payType, $referrerFee, $recruiter_id, $store->id, 9, $order->id); // 门店推荐人
            $this->agentBill($payType, $groupFee, $groupAgent_id, $store->id, 10, $order->id); // 组代
            $this->agentBill($payType, $groupFee, $groupRecruiter_id, $store->id, 11, $order->id, $groupAgent_id); // 组招
            
        } catch (\Exception $e) {
            \Log::error('代理分成执行失败', [
                'order_id' => $order->id,
                'error' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 给代理分账
     * 对应老项目的 agentBill 静态方法（第483-551行）
     * 
     * @param int $payTypeId 支付类型ID
     * @param float $fee 分成比例
     * @param int $memberId 代理ID
     * @param int $storeId 门店ID
     * @param int $type 分成类型（1=省代,2=市代,3=区代等）
     * @param int $orderId 订单ID
     * @param int|null $profferId 推荐人ID
     * @return void
     */
    private function agentBill($payTypeId, $fee, $memberId, $storeId, $type, $orderId, $profferId = null)
    {
        // 如果代理ID为空或分成为0，跳过
        if (!$memberId || $fee <= 0) {
            return;
        }
        
        try {
            // 获取订单信息 - 第491-494行
            $order = \App\Models\Order::where('id', $orderId)->first();
            if (!$order) {
                return;
            }
            
            $price = $order->price;
            $consume_id = $order->uid;
            $order_sn = $order->order_sn;
            
            // 验证会员是否存在 - 第495行
            $member = \App\Models\Member::where('uid', $memberId)->first();
            if (!$member) {
                return;
            }
            
            // 根据支付类型分配 - 第497-542行
            if ($payTypeId == 133) {
                // ===== 分茶包 - 第497-504行 =====
                $memberLove = \App\Models\LoveMember::where('member_id', $memberId)->first();
                if ($memberLove) {
                    $usable = round((float)$memberLove->usable, 2);
                    $addAmount = round($fee * $price, 2);
                    $newusable = round($usable + $addAmount, 2);
                    $memberLove->usable = $newusable;
                    $memberLove->updated_at = time();
                    $memberLove->save();
                    
                    \Log::info('代理分成-茶包', [
                        'member_id' => $memberId,
                        'type' => $type,
                        'old_usable' => $usable,
                        'new_usable' => $newusable,
                        'add_amount' => $addAmount
                    ]);
                }
                
            } elseif ($payTypeId == 137) {
                // ===== 分沐浴露 - 第506-541行 =====
                $coin = round($fee * $price, 2);
                $old_coin = 0;
                $new_coin = 0;
                
                // 查询代理的沐浴露余额（consume_type=3）- 第510行
                $rece_user = \App\Models\BreedUserCoin::where([
                    'user_id' => $memberId,
                    'consume_type' => 3
                ])->first();
                
                if ($rece_user) {
                    // 更新余额 - 第511-516行
                    $rece_user_num = round((float)$rece_user->num, 2);
                    $newcoin = round($rece_user_num + $coin, 2);
                    $old_coin = $rece_user_num;
                    $new_coin = $newcoin;
                    
                    $rece_user->num = $newcoin;
                    $rece_user->updated_at = time();
                    $rece_user->save();
                } else {
                    // 创建新记录 - 第517-522行
                    $record = new \App\Models\BreedUserCoin();
                    $record->uniacid = 1;
                    $record->user_id = $memberId;
                    $record->consume_type = 3;
                    $record->num = $coin;
                    $record->created_at = time();
                    $record->updated_at = time();
                    $record->save();
                    $new_coin = $coin;
                }
                
                // 获取备注 - 第524-528行
                $remark = '代理分成,商家ID:';
                if ($type == 10 || $type == 11) {
                    $remark = '区域分组奖,商家ID:';
                }
                
                // 创建沐浴露流水记录 - 第529-540行
                \App\Models\BreedCoinFlow::create([
                    'uniacid' => 1,
                    'send_user' => 0,
                    'rec_user' => $memberId,
                    'num' => $coin,
                    'type' => 11,
                    'consume_type' => 3,
                    'old_coin' => $old_coin,
                    'new_coin' => $new_coin,
                    'remark' => $remark . $storeId,
                    'created_at' => time(),
                    'updated_at' => time()
                ]);
                
                // 创建佣金流水记录 - 第541行
                $this->addCoinFlow($memberId, $consume_id, $coin, $storeId, $type, $old_coin, $new_coin, $price, $order_sn, $profferId);
            }
            
        } catch (\Exception $e) {
            \Log::error('代理分账失败', [
                'member_id' => $memberId,
                'type' => $type,
                'error' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 添加佣金流水记录
     * 对应老项目的 addCoinFlow 静态方法（第554-592行）
     * 
     * @param int $benefitId 受益人ID
     * @param int $consumeId 消费者ID
     * @param float $num 金额
     * @param int $storeId 门店ID
     * @param int $type 分成类型
     * @param float $oldCoin 旧余额
     * @param float $newCoin 新余额
     * @param float $price 订单金额
     * @param string $orderSn 订单号
     * @param int|null $profferId 推荐人ID
     * @return void
     */
    private function addCoinFlow($benefitId, $consumeId, $num, $storeId, $type, $oldCoin, $newCoin, $price, $orderSn, $profferId = null)
    {
        try {
            // 获取门店信息 - 第556行
            $store = \App\Models\Store::where('id', $storeId)->first();
            if (!$store) {
                return;
            }
            
            // 获取省市区名称 - 第557-565行
            $province_id = $store->province_id;
            $province = \App\Models\Address::where('id', $province_id)->first();
            $province_name = $province ? $province->areaname : '';
            
            $city_id = $store->city_id;
            $city = \App\Models\Address::where('id', $city_id)->first();
            $city_name = $city ? $city->areaname : '';
            
            $district_id = $store->district_id;
            $district = \App\Models\Address::where('id', $district_id)->first();
            $district_name = $district ? $district->areaname : '';
            
            // 获取备注 - 第567行
            $remark = '代理分成,商家ID:' . $storeId;
            
            // 创建佣金流水记录 - 第568-591行
            \App\Models\BreedCommissionCoinFlow::create([
                'uniacid' => 1,
                'type' => $type,
                'consume_type' => 3,
                'remark' => $remark,
                'coin_type' => 1,
                'store_id' => $storeId,
                'benefit_id' => $benefitId,
                'consume_id' => $consumeId,
                'levelId' => 8,
                'province_id' => $province_id,
                'province_name' => $province_name,
                'city_id' => $city_id,
                'city_name' => $city_name,
                'district_id' => $district_id,
                'district_name' => $district_name,
                'num' => $num,
                'old_coin' => $oldCoin,
                'new_coin' => $newCoin,
                'price' => $price,
                'order_sn' => $orderSn,
                'proffer_id' => $profferId,
                'created_at' => time(),
                'updated_at' => time()
            ]);
            
        } catch (\Exception $e) {
            \Log::error('添加佣金流水失败', [
                'benefit_id' => $benefitId,
                'error' => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 结算沐浴露给商家
     * 对应老项目的 BreedChangeService::sendUserCoin
     * 
     * @param array $params 结算参数
     * @return void
     */
    private function settlementBreedCoin($params)
    {
        $storeUid = $params['store_uid'];
        $orderId = $params['order_id'];
        $outTypeAttribute = $params['out_type_attribute']; // 沐浴露类型ID（int）
        $settlementNum = $params['settlement_num']; // 结算比例
        $amount = $params['amount']; // 订单金额
        $orderSn = $params['order_sn'];
        
        // 计算结算金额（保留两位小数）
        $settlementAmount = round($amount * $settlementNum / 100, 2);
        
        // 使用配置的沐浴露类型（out_type_attribute 直接是 consume_type）
        $consumeType = $outTypeAttribute ?: 6; // 默认类型6
        
        $breedUserCoin = \App\Models\BreedUserCoin::where([
            'user_id' => $storeUid,
            'consume_type' => $consumeType
        ])->first();
        
        if ($breedUserCoin) {
            $oldNum = round((float)$breedUserCoin->num, 2);
            $newNum = round($oldNum + $settlementAmount, 2);
            $breedUserCoin->num = $newNum;
            $breedUserCoin->updated_at = time();
            $breedUserCoin->save();
        } else {
            // 创建新记录
            $oldNum = 0;
            $newNum = $settlementAmount;
            $breedUserCoin = new \App\Models\BreedUserCoin();
            $breedUserCoin->uniacid = 1;
            $breedUserCoin->user_id = $storeUid;
            $breedUserCoin->num = $settlementAmount;
            $breedUserCoin->consume_type = $consumeType;
            $breedUserCoin->created_at = time();
            $breedUserCoin->updated_at = time();
            $breedUserCoin->save();
        }
        
        // 创建流水记录
        $breedCoinFlow = new \App\Models\BreedCoinFlow();
        $breedCoinFlow->uniacid = 1;
        $breedCoinFlow->send_user = 0;
        $breedCoinFlow->rec_user = $storeUid;
        $breedCoinFlow->num = $settlementAmount;
        $breedCoinFlow->type = 10; // 商家结算
        $breedCoinFlow->consume_type = $consumeType;
        $breedCoinFlow->old_coin = $oldNum;
        $breedCoinFlow->new_coin = $newNum;
        $breedCoinFlow->remark = '置换结算,订单号:' . $orderSn;
        $breedCoinFlow->created_at = time();
        $breedCoinFlow->updated_at = time();
        $breedCoinFlow->save();
    }

    /**
     * 结算茶包给商家
     * 类比沐浴露结算，将茶包（Love）余额按结算比例入账到商家
     * 
     * @param array $params ['store_uid','order_id','settlement_amount','order_sn']
     * @return void
     */
    private function settlementTeaBag($params)
    {
        $storeUid = $params['store_uid'];
        $orderId = $params['order_id'] ?? 0;
        $orderSn = $params['order_sn'] ?? '';
        $settlementAmount = round((float)($params['settlement_amount'] ?? 0), 2);

        if ($settlementAmount <= 0 || !$storeUid) {
            return;
        }

        $loveMember = \App\Models\LoveMember::where('member_id', $storeUid)->first();
        $oldUsable = $loveMember ? round((float)$loveMember->usable, 2) : 0.0;
        $newUsable = round($oldUsable + $settlementAmount, 2);

        // 创建茶包变动记录（增加）
        $love = new \App\Models\Love();
        $love->uniacid = 1;
        $love->member_id = $storeUid;
        $love->old_value = $oldUsable;
        $love->change_value = $settlementAmount;
        $love->new_value = $newUsable;
        $love->type = 1; // 增加
        $love->source = 4; // 来源：消费结算（沿用消费源值）
        $love->relation = $orderSn;
        $love->operator = 2;
        $love->operator_id = $orderId;
        $love->remark = '置换结算增加';
        $love->value_type = 1;
        $love->created_at = time();
        $love->updated_at = time();
        $love->save();

        // 更新商家茶包余额
        if ($loveMember) {
            $loveMember->usable = $newUsable;
            $loveMember->updated_at = time();
            $loveMember->save();
        } else {
            $loveMember = new \App\Models\LoveMember();
            $loveMember->uniacid = 1;
            $loveMember->member_id = $storeUid;
            $loveMember->usable = $newUsable;
            $loveMember->updated_at = time();
            $loveMember->created_at = time();
            $loveMember->save();
        }
    }

    /**
     * 结算额度给商家
     * 使用额度（ims_yz_breed_user_coin_quota）作为商家结算资产并记录额度流水
     *
     * @param array $params ['store_uid','order_id','settlement_num','amount','order_sn']
     * @return void
     */
    private function settlementQuota($params)
    {
        $storeUid = $params['store_uid'];
        $orderId = $params['order_id'] ?? 0;
        $orderSn = $params['order_sn'] ?? '';
        $settlementNum = (float)($params['settlement_num'] ?? 0);
        $amount = (float)($params['amount'] ?? 0);

        // 计算结算金额（保留两位小数）
        $settlementAmount = round($amount * $settlementNum / 100, 2);
        if ($settlementAmount <= 0 || !$storeUid) {
            return;
        }

        // 加锁读取/更新商家额度余额
        $record = \DB::table('ims_yz_breed_user_coin_quota')
            ->where('user_id', $storeUid)
            ->lockForUpdate()
            ->first();

        if ($record) {
            $oldNum = round((float)$record->num, 2);
            $newNum = round($oldNum + $settlementAmount, 2);
            \DB::table('ims_yz_breed_user_coin_quota')
                ->where('user_id', $storeUid)
                ->update([
                    'num' => $newNum,
                    'updated_at' => time()
                ]);
        } else {
            $oldNum = 0.00;
            $newNum = $settlementAmount;
            \DB::table('ims_yz_breed_user_coin_quota')->insert([
                'uniacid' => 1,
                'user_id' => $storeUid,
                'num' => $settlementAmount,
                'created_at' => time(),
                'updated_at' => time()
            ]);
        }

        // 写入额度流水（商家结算收入）
        \DB::table('ims_yz_breed_coin_quota_flows')->insert([
            'send_user' => 0,
            'rec_user' => $storeUid,
            'num' => $settlementAmount,
            'uniacid' => 1,
            'created_at' => time(),
            'updated_at' => time(),
            'remark' => '门店置换订单结算，订单号' . $orderSn,
            'old_coin' => $oldNum,
            'new_coin' => $newNum,
            'type' => 3 // 10:商家结算收入
        ]);
    }
    
    /**
     * 获取公共数据
     * 按照老项目 BasicInformation::getPublicData 方法逻辑实现
     *
     * @return array
     */
    private function getPublicData()
    {
        $uid = request()->get('uid', 0); // 从请求中获取用户ID
        
        // 检查缓存
        if (!Cache::has("public_setting")) {
            // 商城设置 - 这里需要根据实际的新项目配置来获取
            $shop_setting = [
                'logo' => 'images/1/2023/11/14a607677429e85ab8bc9573b77b4503.png',
                'signimg' => '',
                'name' => '柚惠易购',
                'copyright' => '柚惠易兑',
                'copyrightImg' => '',
                'achievement' => '0',
                'member_level' => ['-1'],
                'cservice' => '',
                'cservice_mini' => '',
                'baidu' => '',
                'credit' => '余额',
                'credit1' => '',
                'agreement' => '',
                'is_agreement' => 0,
                'agreement_name' => '',
                'diycode' => '',
                'service_mobile' => null
            ];
            
            $member_set = [
                'is_bind_mobile' => 0,
                'mobile_login_code' => 0
            ];
            
            $mailInfo = [
                'logo' => $shop_setting['logo'],
                'signimg' => $shop_setting['signimg'],
                'agent' => true, // 这里需要根据实际配置获取
                'diycode' => $shop_setting['diycode'],
                'is_bind_mobile' => $member_set['is_bind_mobile'],
                'service_mobile' => $shop_setting['service_mobile'],
            ];
            
            $mailInfo = array_merge($shop_setting, $mailInfo);
            $setting['mailInfo'] = $mailInfo;
            $setting['mobile_login_code'] = $member_set['mobile_login_code'];
            $setting['register'] = []; // 注册设置
            $setting['captcha_status'] = 0; // 验证码状态
            $setting['plugin']['goods_show'] = [];
            $setting['love_name'] = '消费励'; // 爱心值名称
            
            Cache::put("public_setting", $setting, 3600);
        } else {
            $setting = Cache::get("public_setting");
        }
        
        // 强制绑定手机号
        $is_bind_mobile = 0;
        if ($uid) {
            // 查询用户信息
            $member = \App\Models\Member::find($uid);
            if ($member) {
                $is_bind_mobile = $member->mobile ? 0 : $setting['mailInfo']['is_bind_mobile'];
                $result['memberinfo']['uid'] = $member->uid;
                // 用户爱心值 - 这里需要根据实际的爱心值表查询
                $result['memberinfo']['usable'] = $member->credit2 ?? '0.00';
            }
        }
        
        $setting['mailInfo']['is_bind_mobile'] = (int)$is_bind_mobile;
        $result['mailInfo'] = $setting['mailInfo'];
        
        // 验证码
        if (extension_loaded('fileinfo') && $setting['captcha_status'] == 1) {
            $result['captcha'] = [
                'status' => 1,
                'sensitive' => 0,
                'sensitive' => 0
            ];
        }
        
        $result['system']['mobile_login_code'] = $setting['mobile_login_code'] ? 1 : 0;
        $result['system']['btn_romotion'] = '1'; // 推广按钮状态
        
        // 会员注册设置
        $result['register_setting'] = $setting['register'];
        
        // 商品展示组件
        $result['plugin']['goods_show'] = $setting['plugin']['goods_show'];
        $result['plugin']['new_member_prize'] = [];
        
        $result['designer']['love_name'] = $setting['love_name'];
        
        // 视图设置和菜单 - 这里需要根据实际的新项目配置来获取
        $result['item'] = [
            'ViewSet' => [
                'member' => ['is_default' => 0],
                'extension' => ['is_default' => 0],
                'category' => [
                    'id' => 1,
                    'uniacid' => 1,
                    'name' => 'category01',
                    'image' => 'category_01',
                    'code' => 'category01',
                    'type' => 3,
                    'is_default' => 1,
                    'created_at' => '2023-08-14 16:23:41',
                    'updated_at' => '2025-06-21 14:12:51',
                    'deleted_at' => 0
                ],
                'goods' => ['is_default' => 0],
                'goodsList' => ['is_default' => 0]
            ],
            'is_decorate' => 1,
            'menus' => [
                'id' => 1,
                'uniacid' => 1,
                'page_info' => '{"group_title":{"title":"底部导航名称","type":"text","value":"柚惠易购"},"button_item":{"title":"","type":"bottomItem","choose":"2","menu_button":[{"id":0,"text":"首页","image":"","icon":"icon-fontclass-shouye","default_icon":"","isIcon":"1","link":"http://yidui.jiujiefang7979.cn/addons/yun_shop/?menu#/newDiy?page_id=7&i=1","app_link":{},"isMinApp":"1","gh_id":"","minApp_link":"","sub_button":[]},{"id":1,"text":"分类","image":"","icon":"","default_icon":"","isIcon":"1","link":"https://yidui.jiujiefang7979.cn/addons/yun_shop/?menu#/category?i=1","app_link":{},"isMinApp":"1","gh_id":"","minApp_link":"","sub_button":[]},{"id":2,"text":"购物车","image":"","icon":"icon-fontclass-gouwuche1","default_icon":"","isIcon":"1","link":"http://yidui.jiujiefang7979.cn/addons/yun_shop/?menu#/cart?i=1","app_link":{},"isMinApp":"1","gh_id":"","minApp_link":"","sub_button":[]},{"id":3,"text":"会员中心","image":"","icon":"icon-fontclass-huiyuanzhongxin","default_icon":"","isIcon":"1","link":"http://yidui.jiujiefang7979.cn/addons/yun_shop/?menu#/member?i=1","app_link":{},"isMinApp":"1","gh_id":"","minApp_link":"","sub_button":[]}],"value":[]},"tab_style":{"title":"","type":"tab","value":{"text_set":{"text_show":true,"text_color":"#333333","text_choose_color":"#29ba9c"},"icon_set":{"icon_show":true,"icon_position":"top","icon_color":"#333333","icon_choose_color":"#29ba9c"},"border_set":{"border_show":false,"border_color":"#e7e7eb","border_choose_color":"#29ba9c"},"bg_set":{"bg_color":"#ffffff","bg_choose_color":"#ffffff"},"children_set":{"children_color":"#333333","children_choose_color":"#29ba9c","children_bg_color":"#ffffff"}}}}',
                'name' => '柚惠易购',
                'page_sort' => 1,
                'is_default' => 1,
                'created_at' => '2023-02-02 16:53:25',
                'updated_at' => '2023-11-08 10:27:38',
                'deleted_at' => 0
            ]
        ];
        
        return $result;
    }
}